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 8 years ago.
Improve this question
I defined a function that generates some names and I run from loop:
output = open('/tmp/NameGen-output.txt', 'w')
while True:
var = NameGen(name)
.
.
.
if sth:
output.write(var)
elif other:
output.write(var)
break
else:
break
output.close()
update:
first iteration ,content of NameGen-output.txt:
a
b
c
second iteration:
a
b
c
d
e
and etc
So if I overwrite it the second iteration would be just:
d
e
What I am going to ask is:
As you see var equals NameGen() and for each iteration content of var is written to NameGen-output.txt but I want to overwrite output of for each iteration of NameGen() to NameGen-output.txt no appending to it.
Could you possibly help me?
Thank you
You can truncate the existing file without opening and closing it, and flush to ensure that it is written to:
output = open('/tmp/NameGen-output.txt', 'w')
while True:
var = NameGen()
.
.
.
if not sth and not other:
break
else:
output.flush()
output.seek(0)
output.truncate()
output.write(var)
output.flush()
output.write(var)
if other:
break
output.close()
You could move the file opening (note: using with context manager is preferred) inside the loop:
while True:
var = NameGen()
...
with open('/tmp/NameGen-output.txt', 'w') as output:
output.write(var)
...
...
Related
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 2 years ago.
Improve this question
I have a function that creates a dictionary based on the user's input:
def store_data(user_inp):
list_of_letters = list(user_inp)
list_of_colons = []
nested_dict = {}
for letter in list_of_letters:
if letter == ':':
list_of_colons.append(letter)
if len(list_of_colons) == 2:
str1 = ''.join(list_of_letters)
list2 = str1.split(':')
main_key = list2[0]
nested_key = list2[1]
value = list2[2]
if main_key not in storage:
storage[main_key] = nested_dict
nested_dict[nested_key] = value
print(storage, '\n', 'successfully saved!')
elif main_key in storage:
if nested_key in storage[main_key]:
print('this item is already saved: \n', storage)
else:
storage[main_key][nested_key] = value
print(storage, '\n', 'successfully saved!')
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
f.close()
What i'm trying to do is to store the final dictionary somewhere permanent.
I tried this at the end of my function but it doesn't seem to work:
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
f.close()
How can I store the final dictionary so it's permanent but still editable?
You can save it to a .json file as you did. After that, you can still edit the variable that you pasted. So you could create a thread that auto-saves every 10 minutes or so by invoking
jf = json.dumps(storage)
with open('myStorage.json', 'w') as f:
f.write(jf)
PS: You don't need to care about f.close() if you are using with open(...) :)
If you can't tell what is happening where I highly suggest printing the current state of storage before entering a new if clause
I'm sorry but I am unable to debug your code because there are to many variables undefined...
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
Im trying to read two files and print them in another two separate files after reading and making some updates. My input file names are big-1.csv and big-2.csv. Therefore Im trying to read these two files using a for loop. For the output im trying to print them with names fix-1.csv and fix-2.csv but it seems my for loop is not running for the second time and only running once, while only reading and writing the first big-1.csv file to fix-1.csv file.
My code is :
import csv
from csv import DictWriter
for i in range(1,2):
print(i) #just a flag to check
with open("big-" + str(i) + ".csv") as people_file:
next(people_file)
corrected_people = []
for person_line in people_file:
chomped_person_line = person_line.rstrip()
person_tokens = chomped_person_line.split(",")
# check that each field has the expected type
try:
corrected_person = {
"id": person_tokens[0],
"first_name":person_tokens[1],
"last_name": "".join(person_tokens[2:-3]),
"email":person_tokens[-3],
"gender":person_tokens[-2],
"ip_address":person_tokens[-1]
}
if not corrected_person["ip_address"].startswith(
"") and corrected_person["ip_address"] !="n/a":
raise ValueError
corrected_people.append(corrected_person)
except (IndexError, ValueError):
# print the ignored lines, so manual correction can be performed later.
print("Could not parse line: " + chomped_person_line)
with open("fix-" + str(i) + ".csv", "w") as corrected_people_file:
writer = DictWriter(
corrected_people_file,
fieldnames=[
"id","first_name","last_name","email","gender","ip_address"
],delimiter=',')
writer.writeheader()
writer.writerows(corrected_people)
Th output im getting is :
j:\Programs\Python>python "for loop testing.py"
1
j:\Programs\Python>
And fix-1.csv file. The update part is working fine. The only problem I'm facing is that the for loop is running once. Please note, no indentation error is coming. Please help.
range(1,2) only contains one value (the number 1).
Perhaps you meant
for i in (1,2): # values are 1 and 2
or
for i in range(2): # values are 0 and 1
or
for i in range(1,3): # values are 1 and 2
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 6 years ago.
Improve this question
I want to write in a file which changes the name with the counter.
for j in range(30):
fileout.write("bla bla")
and fileout should be
file001 if j=1
file002 if j=2
...
...
I cannot format it in the right way.
Anyone can help me?
Thank you
You can try to use the .zfill( < number of digits > ) option. It will complet your string with 0.
For example, this code should work :
radical ='file'
numberOfDigits = 3
for j in range( 30 ) :
fileout = open ( radical + '%s' %(str(j).zfill(numberOfDigits)) + '.txt' , 'w' )
fileout.write('bla bla')
fileout.close()
Not sure if below means what you needed ?
Code below will create file000 - file029 with 'bla bla' inside
for i in range(30):
with open("file%03d" % i, 'w') as f:
f.write('bla bla')
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 7 years ago.
Improve this question
[data.txt]
CODE\tUSERNAME\tSPENT\tCOLUM1\tCOLUM2
I want to sort the file [data.txt], using "SPENT". How can i do this?
Yes, of course it is possible. For example:
# read file into array of lines
lines = open("data.txt").readlines()
# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[2])
The lambda extrudes the SPENT column from the row to be used as sorting-key.
def subMenu_5():
# read file into array of lines
lines = open("database").readlines()
# sort those lines using a lambda
lines.sort(key = lambda line : line.split("\t")[3])
clientList = []
dataQuantify = 0
database = open('database','r')
i = 1
while (i == 1):
if (database.readline() == ''):
i = 0
else:
dataQuantify = dataQuantify + 1
database.close()
sortList = open("sortList","w")
for i in range (3):
sortList.write(lines[i])
sortList.close()
print "[Código] [Nome] [Quant. Prod. Comprados] [Valor Gasto] [Descontos] \n"
sortList = open('sortList','r')
i = 0
while (i < dataQuantify):
clientList.append(sortList.readline())
print clientList[i]
i = i + 1
database.close()
raw_input("Precione 'ENTER' para voltar ao menu principal... ")
return
This work! Very Thx!
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 8 years ago.
Improve this question
I'm trying to make a config reader in Python. The config has the following structure:
#section:
property = 'value'
end
#section2:
property2 = 'value'
end
The config is managed using two functions:
getValue(file, section, property)
setValue(file, section, property, newvalue)
But I don't know how to do the parser. Help plz :\
That was interesting. This should work perfectly. I wasn't sure whether to strip out the single quotes you had next to your values, but I decided to take them out for cleanliness of output.
with open('configfile.cfg') as f:
data = f.readlines()
config = {}
current_section = None
for line in data:
line = line.strip()
if line == 'end' or not line:
continue
if line.startswith('#'):
current_section = line[1:-1]
config[current_section] = {}
else:
key, value = line.split('=')
config[current_section][key.strip()] = value.strip().strip("'")
print(config)
For future reference, it's a lot easier to help if you give a small bit of actual data and then describe the data, rather than giving names that are types. For example, I used this as a config file:
#section:
red = '3three'
end
#section2:
blue = '4four'
green = '5five'
end
and here's the output dict for that config file:
{'section': {'red': '3three'}, 'section2': {'blue': '4four', 'green': '5five'}}