This question already has answers here:
How do I append to a file?
(13 answers)
Closed 6 years ago.
I want to read and write files multiple times.But the way is failed,it only writes the last modified content rather than all modified contents.
The incorrect program
def openfile():
txt = open("test.txt", "r")
contents = txt.readlines()
txt.close()
return contents
def write_file(contents,f):
old_contents = openfile()
old_contents.insert(1,contents)
contents = "".join(old_contents )
f.write(contents)
f.close()
text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)
text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)**
Worry Output
test2
My hope output
test1
test2
This is too much of code for the File Open and Write, You can just use this following lines to append the text in your file
def FileSave(filename,content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")
Here, when we using this line open(filename, "a"), the a indicates the appending the file, that means allow to insert extra data to the existing file
as stated in the python doc you need to open your file with mode='a' if you want to append to existing data; mode='w' simply overwrites:
with open(file='_test.txt', mode='a') as file:
file.write('test')
(if you are using python 2, change the variable name file above to something else; in python 2 file is a keyword).
The reason for your "Worry Output" is that you re-open "test.txt" in read mode inside openfile after you've already opened it in write mode outside the functions. When you open a file in write mode it gets truncated, i.e., the file pointer is positioned to the start of the file and the current contents of the file are discarded. So when you call openfile inside write_file the file is empty, and thus openfile returns an empty list.
Here's a repaired version of your code. We use try... except in openfile so we can return an empty list if the file doesn't exist.
def openfile(fname):
try:
f = open(fname, "r")
contents = f.readlines()
f.close()
return contents
except FileNotFoundError:
return []
def write_file(contents, fname):
old_contents = openfile(fname)
old_contents.insert(1,contents)
contents = "".join(old_contents)
f = open(fname, "w")
f.write(contents)
f.close()
contents= "test1 \n"
write_file(contents, "test.txt")
contents = "test2 \n"
write_file(contents, "test.txt")
And here are the contents of "test.txt" after running that code:
test1
test2
Actually, it's better to use with when opening files:
def openfile(fname):
try:
with open(fname, "r") as f:
contents = f.readlines()
return contents
except FileNotFoundError:
return []
def write_file(contents, fname):
old_contents = openfile(fname)
old_contents.insert(1,contents)
contents = "".join(old_contents)
with open(fname, "w") as f:
f.write(contents)
However, a much better way to do this is to simply open the file in append mode as hiro protagonist and K.Suthagar have already shown. But I figured it was a good idea to explain why your current code didn't do what you expected it to do.
text1 = open("test.txt","w")
It is because above code resets the content. "w" is to override the file content.
Below code should explain you where you went wrong-
def openfile():
txt = open("test.txt", "r")
contents = txt.readlines()
print "Openfile method- Contents: "+str(contents)
txt.close()
return contents
def write_file(contents,f):
print "WriteFile method- Content received: "+str(contents)
old_contents = openfile()
print "Writefile method- Old content read from file: "+str(old_contents)
old_contents.insert(1,contents)
print "Writefile method- Old content after insertion: "+str(old_contents)
contents = "".join(old_contents )
print "WriteFile method- Content to write: "+str(contents)
f.write(contents)
f.close()
text1 = open("test.txt","w")
contents= "test1 \n"
write_file(contents,text1)
text2 = open("test.txt","w")
contents = "test2 \n"
write_file(contents,text2)
As mentioned, use "a" to append to file.
Related
I need to write function which given a text file object open in read and write mode and a string, inserts the text of the string in the file at the current read/write position. In other words, the function writes the string in the file without overwriting the rest of it. When exiting the function, the new read/write position has to be exactly at the end of the newly inserted string.
The algorithm is simple; the function needs to:
read the content of the file starting at the current read/write position
write the given string at the same position step 1 started
write the content read at step 1. at the position where step 2. ended
reposition the read/write cursor at the same position step2. ended (and step 3. started)
If the argument file object is not readable or writable, the function should print a message and return immediately without changing anything.
This can be achieved by using the methods file object methods readable() and writable().
In the main script:
1- prompt the user for a filename
2- open the file in read-write mode. If the file is not found, print a message and exit the program
3- insert the filename as the first line of the file followed by an empty line
4- insert a line number and a space, at the beginning of each line of the original text.
I'm very confused on how to write the function and main body.
so far I only have
def openFile(fileToread):
print(file.read())
givefile = input("enter a file name: ")
try:
file = open(givefile, "r+")
readWriteFile = openFile(file)
except FileNotFoundError:
print("File does not exist")
exit(1)
print(givefile, "\n")
which is not a lot.
I need an output like this:
twinkle.txt
1 Twinkle, twinkle, little bat!
2 How I wonder what you're at!
3 Up above the world you fly,
4 Like a teatray in the sky.
the file used is a simple .txt file with the twinkle twinkle song
How can I do this?
Basic solution
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "r") as fd:
file_content = open_file(fd)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{give_file}\n\n{file_content}'
try:
# save the data
with open(give_file, "w") as fd:
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
This should give you the expected result.
I asked about the r+ and how to use it in this case. I got this answer:
reset the cursor to 0 should do the trick
my_fabulous_useless_string = 'POUET'
with open(path, 'r+') as fd:
content = fd.read()
fd.seek(0)
fd.write(f'{my_fabulous_useless_string}\n{content}')
so with your code it's:
give_file = input("enter a file name: ")
def open_file(file):
return file.read()
def save_file(file, content):
file.write(content)
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = open_file(fd)
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
save_file(fd, new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
A suggestion
Don't use function, it hide the fact that a method is used with some side-effects (move the cursor).
Instead, call the method directly, this is better:
give_file = input("enter a file name: ")
try:
# Use this to get the data of the file
with open(give_file, "+r") as fd:
file_content = fd.read()
new_content = f'{give_file}\n\n{file_content}'
fd.seek(0)
fd.write(new_content)
except FileNotFoundError:
print("File does not exist")
exit(1)
Or, with the basic solution and functions
def open_file(path):
with open(path, "r") as fd:
return fd.read()
def save_file(path, content):
with open(path, 'w') as fd:
fd.write(content)
# get file_name
file_name = input("enter a file name: ")
try:
# Use this to get the data of the file
file_content = open_file(file_name)
except FileNotFoundError:
print("File does not exist")
exit(1)
# change the data
new_content = f'{file_name}\n\n{file_content}'
# save the data
save_file(file_name, new_content)
I would like to open a text file named file1.txt, count the length, then close it with the name file2.txt.
I very much prefer not importing anything.
file1 = open('file1.txt')
def wordCount(file1):
contents = file1.read()
file1.close()
print(contents)
return len(contents)
print(wordCount(file1))
It comes out as it should but I have no idea where begin the next step of the process.
# Copying then editing files
local_saved = []
with open("file1.txt", "r") as f:
local_saved.append(f.read())
with open("file2.txt", "w+") as f:
text_to_write = local_saved[0]
# Edit text_to_write below.
# Can be deleted (text_to_write = "") or changed in any way as if it were a normal string.
# ...
f.write(text_to_write)
Here it is:
file1 = open('file1.txt')
def wordCount(file1):
contents = file1.read()
file2=open('file2.txt','w')
file2.write(contents)
file2.close()
file1.close()
print(contents)
return len(contents)
print(wordCount(file1))
Output:
Sorry, this was being awfully awkward when I trying to paste my Python code into the code box on this forum post.
Code:
# update three quotes to a file
file_name = "my_quote.txt"
# create a file called my_quote.txt
new_file = open(file_name, 'w')
new_file.close()
def update_file(file_name, quote):
# First open the file
new_file = open(file_name, 'w')
new_file.write("This is an update\n")
new_file.write(quote)
new_file.write("\n\n")
# now close the file
new_file.close()
for index in range(3):
quote = input("Enter your favorite quote: ")
update_file(file_name, quote)
# Now print the contents to the screen
new_file = open(file_name, 'r')
print(new_file.read())
# And finally close the file
new_file.close(
You should be using append instead of write. When you use write, it creates a new file regardless of what was there before. Try new_file = open(file_name, 'a')
Why is it only writing last input to txt?
Everytime you do open(file_name, 'w') it clears the contents of the file and begins to write from the start of the file.
If you would like to append new content to that file do
open(file_name, 'a')
I guess you should use a instead of w to append to file:
new_file = open(file_name, 'a')
And read the docs before asking of course ;)
Currently I'm using this:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.close()
But the problem is that the old file is larger than the new file. So I end up with a new file that has a part of the old file on the end of it.
If you don't want to close and reopen the file, to avoid race conditions, you could truncate it:
f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()
The functionality will likely also be cleaner and safer using open as a context manager, which will close the file handler, even if an error occurs!
with open(filename, 'r+') as f:
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
The fileinput module has an inplace mode for writing changes to the file you are processing without using temporary files etc. The module nicely encapsulates the common operation of looping over the lines in a list of files, via an object which transparently keeps track of the file name, line number etc if you should want to inspect them inside the loop.
from fileinput import FileInput
for line in FileInput("file", inplace=1):
line = line.replace("foobar", "bar")
print(line)
Probably it would be easier and neater to close the file after text = re.sub('foobar', 'bar', text), re-open it for writing (thus clearing old contents), and write your updated text to it.
I find it easier to remember to just read it and then write it.
For example:
with open('file') as f:
data = f.read()
with open('file', 'w') as f:
f.write('hello')
To anyone who wants to read and overwrite by line, refer to this answer.
https://stackoverflow.com/a/71285415/11442980
filename = input("Enter filename: ")
with open(filename, 'r+') as file:
lines = file.readlines()
file.seek(0)
for line in lines:
value = int(line)
file.write(str(value + 1))
file.truncate()
Honestly you can take a look at this class that I built which does basic file operations. The write method overwrites and append keeps old data.
class IO:
def read(self, filename):
toRead = open(filename, "rb")
out = toRead.read()
toRead.close()
return out
def write(self, filename, data):
toWrite = open(filename, "wb")
out = toWrite.write(data)
toWrite.close()
def append(self, filename, data):
append = self.read(filename)
self.write(filename, append+data)
Try writing it in a new file..
f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
I am very new to programming and the python language.
I know how to open a file in python, but the question is how can I open the file as a parameter of a function?
example:
function(parameter)
Here is how I have written out the code:
def function(file):
with open('file.txt', 'r') as f:
contents = f.readlines()
lines = []
for line in f:
lines.append(line)
print(contents)
You can easily pass the file object.
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable.
and in your function, return the list of lines
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
Another trick, python file objects actually have a method to read the lines of the file. Like this:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
With the second method, readlines is like your function. You don't have to call it again.
Update
Here is how you should write your code:
First method:
def function(file):
lines = []
for line in f:
lines.append(line)
return lines
with open('file.txt', 'r') as f: #open the file
contents = function(f) #put the lines to a variable (list).
print(contents)
Second one:
with open('file.txt', 'r') as f: #open the file
contents = f.readlines() #put the lines to a variable (list).
print(contents)
Hope this helps!
Python allows to put multiple open() statements in a single with. You comma-separate them. Your code would then be:
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after the name before appending the line to the output file.
'''
with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile:
for line in infile:
if line.startswith(txt):
line = line[0:len(txt)] + ' - Truly a great person!\n'
outfile.write(line)
# input the name you want to check against
text = input('Please enter the name of a great person: ')
letsgo = filter(text,'Spanish', 'Spanish2')
And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.)
def fun(file):
contents = None
with open(file, 'r') as fp:
contents = fp.readlines()
## if you want to eliminate all blank lines uncomment the next line
#contents = [line for line in ''.join(contents).splitlines() if line]
return contents
print fun('test_file.txt')
or you can even modify this, such a way it takes file object as a function arguement as well
Here's a much simpler way of opening a file without defining your own function in Python 3.4:
var=open("A_blank_text_document_you_created","type_of_file")
var.write("what you want to write")
print (var.read()) #this outputs the file contents
var.close() #closing the file
Here are the types of files:
"r": just to read a file
"w": just to write a file
"r+": a special type which allows both reading and writing of the file
For more information see this cheatsheet.
def main():
file=open("chirag.txt","r")
for n in file:
print (n.strip("t"))
file.close()
if __name__== "__main__":
main()
the other method is
with open("chirag.txt","r") as f:
for n in f:
print(n)