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 ;)
Related
So i wrote a little program in python which allows me to take a .csv file, filter out the lines i need and then export these into a new .txt file.
This worked quite well, so i decided to make it more user friendly by allowing the user to select the file that should be converted by himself through the console (command line).
My problem: The file is imported as a .csv file but not exported as a .txt file which leads to my program overwriting the original file which will be emptied because of a step in my program which allows me to delete the first two lines of the output text.
Does anyone know a solution for this?
Thanks :)
import csv
import sys
userinput = raw_input('List:')
saveFile = open(userinput, 'w')
with open(userinput, 'r') as file:
reader = csv.reader(file)
count = 0
for row in reader:
print(row[2])
saveFile.write(row[2] + ' ""\n')
saveFile.close()
saveFile = open(userinput, 'r')
data_list = saveFile.readlines()
saveFile.close()
del data_list[1:2]
saveFile = open(userinput, 'w')
saveFile.writelines(data_list)
saveFile.close()
Try This:
userinput = raw_input('List:')
f_extns = userinput.split(".")
saveFile = open(f_extns[0]+'.txt', 'w')
I think you probably just want to save the file with a new name, this Extracting extension from filename in Python talks about splitting out the extension so then you can just add your own extension
you would end up with something like
name, ext = os.path.splitext(userinput)
saveFile = open(name + '.txt', 'w')
You probably just need to change the extension of the output file. Here is a solution that sets the output file extension to .txt; if the input file is also .txt then there will be a problem, but for all other extensions of the input file this should work.
import csv
import os
file_name = input('Name of file:')
# https://docs.python.org/3/library/os.path.html#os.path.splitext
# https://stackoverflow.com/questions/541390/extracting-extension-from-filename-in-python
file_name, file_ext_r = os.path.splitext(file_name)
file_ext_w = '.txt'
file_name_r = ''.format(file_name, file_ext_r)
file_name_w = ''.format(file_name, file_ext_w)
print('File to read:', file_name_r)
print('File to write:', file_name_w)
with open(file_name_r, 'r') as fr, open(file_name_w, 'w') as fw:
reader = csv.reader(fr)
for i, row in enumerate(reader):
print(row[2])
if i >= 2:
fw.write(row[2] + ' ""\n')
I also simplified your logic to avoid writting the first 2 lines to the output file; no need to read and write the output file again.
Does this work for you?
I'm trying to loop through a file, strip the sentences into individual lines, and then export that data.
filename = '00000BF8_ar.txt'
with open(filename, mode="r") as outfile:
str_output = outfile.readlines()
str_output = ''.join(str_output)
sentenceSplit = filter(None, str_output.split("."))
for s in sentenceSplit:
print(s.strip() + ".")
#output += s
myfile = open(filename, 'w')
myfile.writelines(s)
myfile.close()
Unfortunately, it looks like the loop only goes through a few lines and saves them. So the whole file isn't looped through and saved. Any help on how I can fix that?
Here is the code I hope this is what you want to achieve,
filename = '00000BF8_ar.txt'
with open(filename, mode="r") as outfile:
str_output = outfile.readlines()
str_output = ''.join(str_output)
sentenceSplit = filter(None, str_output.split("."))
l=[]
for s in sentenceSplit:
l.append(s.strip() + ".")
myfile = open(filename, 'w')
myfile.write('\n'.join(l))
myfile.close()
Each time you re-open the file with the 'w' option, you basically erase its content.
Try modifying your code like this:
filename = '00000BF8_ar.txt'
with open(filename, "r") as infile:
str_output = infile.readlines()
str_output = ''.join(str_output)
sentenceSplit = filter(None, str_output.split("."))
with open(filename, "w") as outfile:
for s in sentenceSplit:
print(s.strip() + ".")
#output += s
s.writelines(s)
Another way to achieve the same thing would have been to open a new file using open(filename_new, 'a') which open a file for appending, but as a rule of thumb try not to open/close files inside a loop.
open(filename, 'w') will overwrite the file every time it starts. My guess is that what's currently happening is that only the last element in sentenceSplit is showing up in myfile.
The simple "solution" is to use append instead of write:
open(filename, 'a')
which will simply start writing at the end of the file, without deleting the rest of it.
However, as #chepner's comment states, why are you reopening the file at all? I would recommend changing your code to this:
with open(filename, mode="r") as outfile:
str_output = outfile.readlines()
str_output = ''.join(str_output)
sentenceSplit = filter(None, str_output.split("."))
with open(filename, mode='w') as myfile:
for s in sentenceSplit:
print(s.strip() + ".")
myfile.writelines(s)
This way, instead of opening it many times, and overwriting it every time, you're only opening it once and just writing to it continuously.
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.
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)