This question already has answers here:
How do I append to a file?
(13 answers)
Closed 7 years ago.
I have a file called output.txt, which I want to write into from a few functions around the code, some of which are recursive.
Problem is, every time I write I need to open the file again and again and then everything I wrote before is deleted.
I am quite sure there is a solution, didn't find it in all questions asked here before..
def CutTable(Table, index_to_cut, atts, previousSv, allOfPrevSv):
print ('here we have:')
print atts
print index_to_cut
print Table[2]
tableColumn=0
beenHere = False
for key in atts:
with open("output.txt", "w") as f:
f.write(key)
and from another function:
def EntForAttribute(possibles,yesArr):
svs = dict()
for key in possibles:
svs[key]=(yesArr[key]/possibles[key])
for key in possibles:
with open("output.txt", "w") as f:
f.write(key)
All output I have is the last one written in one of the functions..
You need to change the second flag when opening the file:
w for only writing (an existing file with the same name will be
erased)
a opens the file for appending
Your code then should be:
with open("output.txt", "a") as f:
Every time you enter and exit the with open... block, you're reopening the file. As the other answers mention, you're overwriting the file each time. In addition to switching to an append, it's probably a good idea to swap your with and for loops so you're only opening the file once for each set of writes:
with open("output.txt", "a") as f:
for key in atts:
f.write(key)
I believe you need to open the file in append mode (as answered here: append to file in python) like this:
with open("output.txt", "a") as f:
## Write out
Short answer. change the 'w' in the file descriptor to 'a' for append.
with open("test.txt", "a") as myfile:
myfile.write("appended text")
this has already been answered in this thread.
How do you append to a file?
Related
This question already has answers here:
How to erase the file contents of text file in Python?
(13 answers)
Closed last year.
I would like to delete all the contents of my file first, then write on it. How do I do that with a simple file? `
fileHandle = open("file.txt","w")
fileHandle.write(randomVar)
fileHandle.close()
What you need is to open the file in a truncating mode. These are "w" and "w+". Your current code uses "w", so it should work fine!
In python:
open('file.txt', 'w').close()
Or alternatively, if you have already an opened file:
f = open('file.txt', 'r+')
f.truncate(0) # need '0' when using r+
https://stackoverflow.com/a/2769090/17773920
whenever using open(filename,'w') all the content of the data will be overwritten.
If you wish to add content to the file you should be using open(filename,'a').
In addition, I would recommend opening the file using
with open('filename','mode') as f: your code here
as it will provide context manager, making sure the file will closed when you are done with it.
This question already has answers here:
Is there a need to close files that have no reference to them?
(6 answers)
Does reading an entire file leave the file handle open?
(4 answers)
Closed 1 year ago.
I am reading some data from a .txt file in Python using the following:
fileData = open("file.txt", "rb").read()
I know that you should always close opened files, and I assume in this case the file remains open. Is there a way to close the file without assigning it to a variable?
I'd like to avoid:
openedFile = open("file.txt", "rb")
fileData = openedFile.read()
openedFile.close()
And also:
with open("file.txt", "rb") as openedFile:
fileData = openedFile.read()
It might not be possible, in which case okay, but just making sure.
No, it's not possible. The with statement version is the idiomatic way to write it.
Though I would shorten openedFile to file or even f. Rule of thumb: The smaller the scope of a variable the shorter its name can be. Save the long names for long-lived identifiers.
with open("file.txt", "rb") as file:
data = file.read()
This question already has answers here:
Why does my text file keep overwriting the data on it?
(3 answers)
Closed 2 years ago.
So, I did this python program and whenever I run it it says in the file "This is an update" and only one of the quotes I entered. Any help? Program below.
file_name = "my_quote.txt"
new_file = open(file_name, "w")
new_file.close()
def update_file(file_name,quote):
new_file = open(file_name, "w")
new_file.write("This is an update\n")
new_file.write(quote)
new_file.write("\n\n")
new_file.close()
for index in range(1,3):
quote = input("Enter your favorite quote:")
update_file(file_name, quote)
new_file = open(file_name, "r")
print(new_file.read())
new_file.close()
You're opening your file in w mode, which overwrites the file.
Use a for append mode, which, well, appends new content at the end.
You are writing over the current file as you are not opening the file in append mode.
If you change the open command to this instead:
file.open(file_path, 'a')
You will append the text instead of writing over the file.
Whenever you re-open a file, and use write it removes all content previously in the file and overwrites it. And since every time you call update_file you are re-opening it and writeing to it, only the last piece of info written in the last open will be kept (as all previous data was overwritten.
I think you want to use append mode when writing data to the file. See here for a list of all the modes, and their function.
Hope it helps!
I wrote the following python code snippet to append a lower p character to each line of a txt file:
f = open('helloworld.txt','r')
for line in f:
line+='p'
print(f.read())
f.close()
However, when I execute this python program, it returns nothing but an empty blank:
zhiwei#zhiwei-Lenovo-Rescuer-15ISK:~/Documents/1001/ass5$ python3 helloworld.py
Can anyone tell me what's wrong with my codes?
Currently, you are only reading each line and not writing to the file. reopen the file in write mode and write your full string to it, like so:
newf=""
with open('helloworld.txt','r') as f:
for line in f:
newf+=line.strip()+"p\n"
f.close()
with open('helloworld.txt','w') as f:
f.write(newf)
f.close()
well, type help(f) in shell, you can get "Character and line based layer over a BufferedIOBase object, buffer."
it's meaning:if you reading first buffer,you can get content, but again. it's empty。
so like this:
with open(oldfile, 'r') as f1, open(newfile, 'w') as f2:
newline = ''
for line in f1:
newline+=line.strip()+"p\n"
f2.write(newline)
open(filePath, openMode) takes two arguments, the first one is the path to your file, the second one is the mode it will be opened it. When you use 'r' as second argument, you are actually telling Python to open it as an only reading file.
If you want to write on it, you need to open it in writing mode, using 'w' as second argument. You can find more about how to read/write files in Python in its official documentation.
If you want to read and write at the same time, you have to open the file in both reading and writing modes. You can do this simply by using 'r+' mode.
It seems that your for loop has already read the file to the end, so f.read() return empty string.
If you just need to print the lines in the file, you could move the print into for loop just like print(line). And it is better to move the f.read() before for loop:
f = open("filename", "r")
lines = f.readlines()
for line in lines:
line += "p"
print(line)
f.close()
If you need to modify the file, you need to create another file obj and open it in mode of "w", and use f.write(line) to write the modified lines into the new file.
Besides, it is more better to use with clause in python instead of open(), it is more pythonic.
with open("filename", "r") as f:
lines = f.readlines()
for line in lines:
line += "p"
print(line)
When using with clause, you have no need to close file, this is more simple.
This question already has answers here:
Write and read a list from file
(3 answers)
Closed 8 years ago.
I was wondering how I can save a list entered by the user. I was wondering how to save that to a file. When I run the program it says that I have to use a string to write to it. So, is there a way to assign a list to a file, or even better every time the program is run it automatically updates the list on the file? That would be great the file would ideally be a .txt.
stuffToDo = "Stuff To Do.txt"
WRITE = "a"
dayToDaylist = []
show = input("would you like to view the list yes or no")
if show == "yes":
print(dayToDaylist)
add = input("would you like to add anything to the list yes or no")
if add == "yes":
amount=int(input("how much stuff would you like to add"))
for number in range (amount):
stuff=input("what item would you like to add 1 at a time")
dayToDaylist.append(stuff)
remove = input("would you like to remove anything to the list yes or no")
if add == "yes":
amountRemoved=int(input("how much stuff would you like to remove"))
for numberremoved in range (amountRemoved):
stuffremoved=input("what item would you like to add 1 at a time")
dayToDaylist.remove(stuffremoved);
print(dayToDaylist)
file = open(stuffToDo,mode = WRITE)
file.write(dayToDaylist)
file.close()
You can pickle the list:
import pickle
with open(my_file, 'wb') as f:
pickle.dump(dayToDaylist, f)
To load the list from the file:
with open(my_file, 'rb') as f:
dayToDaylist = pickle.load( f)
If you want to check if you have already pickled to file:
import pickle
import os
if os.path.isfile("my_file.txt"): # if file exists we have already pickled a list
with open("my_file.txt", 'rb') as f:
dayToDaylist = pickle.load(f)
else:
dayToDaylist = []
Then at the end of your code pickle the list for the first time or else update:
with open("my_file.txt", 'wb') as f:
pickle.dump(l, f)
If you want to see the contents of the list inside the file:
import ast
import os
if os.path.isfile("my_file.txt"):
with open("my_file.txt", 'r') as f:
dayToDaylist = ast.literal_eval(f.read())
print(dayToDaylist)
with open("my_file.txt", 'w') as f:
f.write(str(l))
for item in list:
file.write(item)
You should check out this post for more info:
Writing a list to a file with Python
Padraic's answer will work, and is a great general solution to the problem of storing the state of a Python object on disk, but in this specific case Pickle is a bit overkill, not to mention the fact that you might want this file to be human-readable.
In that case, you may want to dump it to disk like such (this is from memory, so there may be syntax errors):
with open("list.txt","wt") as file:
for thestring in mylist:
print(thestring, file=file)
This will give you a file with your strings each on a separate line, just like if you printed them to the screen.
The "with" statement just makes sure the file is closed appropriately when you're done with it. The file keyword param to print() just makes the print statement sort of "pretend" that the object you gave it is sys.stdout; this works with a variety of things, such as in this case file handles.
Now, if you want to read it back in, you might do something like this:
with open("list.txt","rt") as file:
#This grabs the entire file as a string
filestr=file.read()
mylist=filestr.split("\n")
That'll give you back your original list. str.split chops up the string it's being called on so that you get a list of sub-strings of the original, splitting it every time it sees the character you pass in as a parameter.