Python-saving while loop results [closed] - python
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
hello i am trying to save the printed results from this while loop and then upload them to a database
i=0
x=0
n=0
while x < len(round1):
n +=1
print 'match number',n, ':' ,round1[x],scoretop[i],'VS','team:', round1[x+1],scorebottom[i],"\n"
x=x+2
i=i+1
i am totally new to python so sorry if this is an easy question
If you're on some UNIX-like system you can run this and redirect the output to a file like this:
python your-file.py > output.txt
Then you can manually upload the output to your database.
If you want to upload the results automatically you should safe the results in a list, instead of printing them, and then upload them through the API of your database. Look at dg123's answer for details on saving you results in a list.
Make a data structure beforehand and append to it while you are in the loop:
results = [] # A list of the results that
# that we will get in the while loop
i=0
x=0
n=0
while x < len(round1):
n +=1
results.append(' '.join(map(str,
['match number',
n,
':' ,
round1[x],
scoretop[i],
'VS','team:',
round1[x+1],scorebottom[i],"\n"])))
x=x+2
i=i+1
The results will then be saved in the results list, which you can then loop over and send to the database:
for i in results:
send_to_database(i)
Or you can concatenate all the strings together and send them that way if you like:
send_to_database('\n'.join(results))
I assume you want to print to file, you can simply write to a file:
with open('log.txt', 'w') as outfile:
while x < len(round1):
# some operations
out = ' '.join(map(str, ['match number', n, ':', round1[x], scoretop[i], 'VS', 'team:', round1[x+1], scorebottom[i], "\n"]))
outfile.write(out)
If you are working on UNIX machines, just follow the suggestion of #Ich Und Nicht Du
Related
i want to save the responses i get from users through my code so how do i do that [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 1 year ago. Improve this question this is my code and i need a way to store the input i get from the 'a' variable print("Hey Welcome To Mental health chatbot") import time time.sleep(1) a = input("So how are you felling today ").strip().upper() if (a == "NICE") or (a == "GOOD") or (a == "I am good"): print("That's nice to hear") if (a == "BAD") or (a == "NOT NICE") or (a == "IT WAS A BAD DAY"): print("Oh")
The simplest way is to store the value in a file like that : def storeVar(a) : f = open("filename.txt", "w+") # w+ allow to write and create the file if it doesnt exist f.write(a) f.close() #always close a file as soon as you stop using it def readVar() : f = open("filename.txt", "r") a=f.read() f.close() return(a)
How to loop through a csv file and only when it encountered a specific word save it into a list? [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 2 years ago. Improve this question I want to loop through this csv that has country, data, and a number I need to extract. The file looks like this: b'/O_o/\ngoogle.visualization.Query.setResponse({"version":"0.6","reqId":"0output=csv","status":"ok","sig":"1241529276","table":{"cols":[{"id":"A","label":"Entity","type":"string"},{"id":"B","label":"Week","type":"number","pattern":"General"},{"id":"C","label":"Day","type":"date","pattern":"yyyy-mm-dd"},{"id":"D","label":"Flights 2019 (Reference)","type":"number","pattern":"General"},{"id":"E","label":"Flights","type":"number","pattern":"General"},{"id":"F","label":"% vs 2019 (Daily)","type":"number","pattern":"General"},{"id":"G","label":"Flights (7-day moving average)","type":"number","pattern":"General"},{"id":"H","label":"% vs 2019 (7-day Moving Average)","type":"number","pattern":"General"},{"id":"I","label":"Day 2019","type":"date","pattern":"yyyy-mm-dd"},{"id":"J","label":"Day Previous Year","type":"date","pattern":"yyyy-mm-dd"},{"id":"K","label":"Flights Previous Year","type":"number","pattern":"General"}],"rows":[{"c":[{"v":"Albania"},{"v":36.0,"f":"36"},{"v":"Date(2020,8,1)","f":"2020-09-01"},{"v":129.0,"f":"129"},{"v":64.0,"f":"64"},{"v":-0.503875968992248,"f":"-0,503875969"},{"v":71.5714285714286,"f":"71,57142857"},{"v":-0.291371994342291,"f":"-0,2913719943"},{"v":"Date(2019,8,3)","f":"2019-09-03"},{"v":"Date(2019,8,3)","f":"2019-09-03"},{"v":129.0,"f":"129"}]},{"c":[{"v":"Albania"},{"v":36.0,"f":"36"},{"v":"Date(2020,8,2)","f":"2020-09-02"},{"v":92.0,"f":"92"},{"v":59.0,"f":"59"},{"v":-0.358695652173913,"f":"-0,3586956522"},{"v":70.0,"f":"70"},{"v":-0.300998573466476,"f":"-0,3009985735"},{"v":"Date(2019,8,4)","f":"2019-09-04"},{"v":"Date(2019,8,4)","f":"2019-09-04"},{"v":92.0,"f":"92"}]},{"c":[{"v":"Albania"},{"v":36.0,"f":"36"},{"v":"Date(2020,8,3)","f":"2020-09-03"},{"v":96.0,"f":"96"},{"v":67.0,"f":"67"},{"v":-0.302083333333333,"f":"-0,3020833333"},{"v":70.1428571428571,"f":"70,14285714"},{"v":-0.30354609929078,"f":"-0,3035460993"},{"v":"Date(2019,8,5)","f":"2019-09-05"},{"v":"Date(2019,8,5)","f":"2019-09-05"},{"v":96.0,"f":"96"}]},{"c":[{"v":"Albania"},{"v":36.0,"f":"36"},{"v":"Date(2020,8,4)","f":"2020-09-04"},{"v":103.0,"f":"103"},{"v":89.0,"f":"89"},{"v":-0.135922330097087,"f":"-0,1359223301"},{"v":69.2857142857143,"f":"69,28571429"},{"v":-0.312056737588652,"f":"-0,3120567376"},{"v":"Date(2019,8,6)","f":"2019-09-06"},{"v":"Date(2019,8,6)","f":"2019-09-06"},{"v":103.0,"f":"103"}]},{"c":[{"v":"Albania"},{"v":36.0,"f":"36"},{"v":"Date(2020,8,5)","f":"2020-09-05"},{"v":94.0,"f":"94"},{"v":53.0,"f":"53"},{"v":-0.436170212765957,"f":"-0,4361702128"},{"v":68.8571428571429,"f":"68,85714286"},{"v":-0.314366998577525,"f":"-0,3143669986"},{"v":"Date(2019,8,7)","f":"2019-09-07"},{"v":"Date(2019,8,7)","f":"2019-09-07"},{"v":94.0,"f":"94"}]}, ... In there it says Albania, which is a country with data I need to extract. For example: {"c":[{"v":"Albania"},{"v":36.0,"f":"36"},{"v":"Date(2020,8,4)","f":"2020-09-04"},{"v":103.0,"f":"103"},{"v":89.0,"f":"89"},{"v":-0.135922330097087,"f":"-0,1359223301"},{"v":69.2857142857143,"f":"69,28571429"},{"v":-0.312056737588652,"f":"-0,3120567376"},{"v":"Date(2019,8,6)","f":"2019-09-06"},{"v":"Date(2019,8,6)","f":"2019-09-06"},{"v":103.0,"f":"103"}]} How would I write a python script to loop over the entire csv file and find every occurrence of the word "Albania", save it, then go a little further and get the date "2020-09-04", and then get the number -0.1359?
You can read this using json. import json with open('txtfile1.txt') as input: data = input.read() #Select the part where the dictionary start (after "rows":) nesteddict = json.loads(data[(data.find('rows')+6):]) finallist = [] for x in nesteddict: sublist = [] sublist.append(x['c'][0]['v']) sublist.append(x['c'][2]['f']) sublist.append(x['c'][5]['v']) finallist.append(sublist) This will output [['Albania', '2020-09-01', -0.503875968992248], ['Albania', '2020-09-02', -0.358695652173913], ['Albania', '2020-09-03', -0.302083333333333], ['Albania', '2020-09-04', -0.135922330097087], ['Albania', '2020-09-05', -0.436170212765957]]
Does this code read the first 10000 lines from a file? [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 2 years ago. Improve this question def read_text(bz2_loc, n=10000): with BZ2File(bz2_loc) as file_: for i, line in enumerate(file_): data = json.loads(line) yield data["body"] if i >= n: break I think it reads each line and return the result immediately, and when it reaches 10000 lines, it jumps out of the loop. This piece of code doesn't complete the reading of the whole file. Is that true? If I want to read the whole file, and yield once for each 10000, how to modify it?
You could try something like this: def read_text(bz2_loc, n=10000): with BZ2File(bz2_loc) as file_: lines = [] for i, line in enumerate(file_): data = json.loads(line) lines.append(data["body"]) if i % n == 0: yield lines lines = [] Just be aware that this will also yield the very first line if i starts at 0
Implementing treeset data structure store and read in VBA / Python/ Shell [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 4 years ago. Improve this question I have a text file like this LEVEL=3 LEVEL1=CLASS7 LEVEL2=ROLLNO1 LEVEL3=MALE JOHN,12 LEVEL2=ROLLNO2 LEVEL3=FEMALE JULIA,11 We need to read this file and need output like CLASS7|ROLLNO1|MALE|JOHN|12 CLASS7|ROLLNO2|FEMALE|JULIA|11 1st LELVEL=3 means maximum LEVEL present in the file. Here LEVEL 1 is common, but in actual data sometimes LEVEL 1 and 3 can be common when maximum LEVEL is say 7.Basically there is no clear pre-defined pattern. I have solved it in VBA using normal array structure but when file becomes very big and maximum LEVEL becomes more( like more than 10) it becomes slow. Then I tried to read more things and came to know using treeset data structure and iterator kind of things it works fast. But this things possible in Java. How we can do it in VBA ? If possible in shell or python that is also ok.
here is a little python approache, but very specific on you string formating, with "text.txt" containing your text: f = open( "text.txt", 'r' ) text = f.readlines() f.close() d = { } for line in text : pair = line.split( '=' ) if len( pair ) == 2 : # save Levels as pairs in dict d[pair[0].strip()] = pair[1].strip() else : line without level means time for output out = [] # gather the values in here try : for i in range( 1, int( d['LEVEL'] ) + 1 ) : # number of levels (1-based) out.append( d['LEVEL' + str( i )] ) # add every level except KeyError : pass out += line.split( ',' ) # add current line out_as_string = '|'.join( out ) # convert to string with "|" print( out_as_string ) outputs: CLASS7|ROLLNO1|MALE|JOHN|12 CLASS7|ROLLNO2|FEMALE|JULIA|11
struggling with python homework [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 5 years ago. Improve this question I got a .txt file with some lines in it: 325255, Jan Jansen 334343, Erik Materus 235434, Ali Ahson 645345, Eva Versteeg 534545, Jan de Wilde 345355, Henk de Vries Write a program that starts with opening the file kaartnummers.txt Determine the number of lines and the largest card number in the file. Then print these data. my code isnt finished yet but i tried atleast!: def kaartinfo(): lst = [] infile = open('kaartnummers.txt', 'r') content = infile.readlines() print(len(content)) for i in content: print(i.split()) kaartinfo() I know that my program opens the file and counts the number of lines in it.. all after that is wrong <3 I can't figure out how to get the max number in the list.. Please if you got an answer use simple readable Python Language.
I'm not good at python, and there are probably much more elegant solutions, but this is how I would do it. Some may say this is like C++/Java in python, which many tend to avoid. def kaartinfo(): lst = [] infile = open('kaartnummers.txt', 'r') content = infile.readlines() for i in content: value = i.split(',') value[0] = int(value[0]) lst.append(value) return lst Use the kaartinfo() function to retrieve a list my_list = kaartinfo() Assume first value is the maximum maximumValue = my_list[0][0] Go through every value in the list, check if they are greater than the current maximum # if they are, set them as the new current maximum for ele in my_list: if ele[0] > maximumValue: maximumValue = ele[0] when the above loop finishes, maximum value will be the largest value in the list. #Convert the integer back to a string, and print the result print(str(maximumValue) + ' is the maximum value in the file!')
This should be enough to do the job: with open('kaartnummers.txt', 'r') as f: data = f.readlines() print('There are %d lines in the file.' % len(data)) print('Max value is %s.' % max(line.split(',')[0] for line in data)) Given the input file you provided, the output would be: There are 6 lines in the file. Max value is 645345. Of course, you can put it in a function if you like.