Python: Write list to file, line by line - python

I want to write the following list to file, each time from new line.
bill_List = [total_price, type_of_menu, type_of_service, amount_of_customers, discount]
I tried to use this code but it just overwrites the text file. Could somebody help me? Where is my mistake?
# attempt #1
f = open("Bills.txt", "w")
f.write("\n".join(map(lambda x: str(x), bill_List)))
f.close()
# attempt #2
# Open a file in write mode
f = open('Bills.txt', 'w')
for item in bill_List:
f.write("%s\n" % item)
# Close opend file
f.close()
# attempt #3
with open('Bills.txt', 'w') as f:
for s in bill_List:
f.write(s + '\n')
with open('Bills.txt', 'r') as f:
bill_List = [line.rstrip('\n') for line in f]
# attempt #4
with open('Bills.txt', 'w') as out_file:
out_file.write('\n'.join(
bill_List))

I think you are looking for 'a' instead of 'w' for the buffering parameter:
with open('Bills.txt', 'a') as out_file:
[...]
See https://docs.python.org/2/library/functions.html?highlight=open#open

Related

Append and Read Same File - Python

Stuck on this school question, what am I missing?
"Objective: Complete the function to append the given new data to the specified file then print the contents of the file"
On of my many attempts:
import os
def appendAndPrint(filename, newData):
with open(filename, 'a') as f:
f = f.write(newData)
r = f.read()
print(r)
Test case, expected output: Hello World
with open("test.txt", 'w') as f:
f.write("Hello ")
appendAndPrint("test.txt", "World")
If I get the interpreter to not throw an error, on several attempts it would simply print 5.
This code should work:
def append_and_print(filename, new_data):
with open(filename, "a") as f:
f.write(new_data)
with open(filename, "r") as f:
print(f.read())
You can open the file with a+ to also give your program read permissions:
import os
def appendAndPrint(filename, newData):
with open(filename, 'a+') as f:
f.write(newData)
f.seek(0)
r=f.read()
print(r)
...
edit: as commenters pointed out, you need to seek to the 0 position in the file so that you can read the whole thing
You can use a+ mode for reading/writing.
After you append using write,
you can move the cursor to the initial position using seek method,
then read it from the beginning.
def appendAndPrint(filename, newData):
with open(filename, 'a+') as f:
f.write(newData)
f.seek(0)
print(f.read())
with open("test.txt", 'w') as f:
f.write("Hello ")
appendAndPrint("test.txt", "World")
Hello World

How to copy a certain part of text from one file to another in python

To extract a certain part of text
in this example I want to extract from d to f
input.txt contains:
a
d
c
b
e
f
g
a
a
the output.txt should contain from d to f
but this program copies from d to last line of input.txt file
f = open('input.txt')
f1 = open('output.txt', 'a')
intermediate_variable=False
for line in f:
if 'd' in line:
intermediate_variable=True
if intermediate_variable==True:
f1.write(line)
f1.close()
f.close()
I think this should do it:
contents = open('input.txt').read()
f1.write(contents[contents.index("d"):contents.index("f")])
There are more convenient ways to read and write files, this version uses a generator and the 'with' keyword (context manager) which automatically closes the file for you. Generators (functions with 'yield' are nice because they give you the file a line at a time, although you have to wrap their output in try/except block)
def reader(filename):
with open(filename, 'r') as fin:
for line in fin:
yield line
def writer(filename, data):
with open(filename, 'w') as fout: #change 'w' to 'a' to append ('w' overwrites)
fout.write(data)
if __name__ == "__main__":
a = reader("input.txt")
while True:
try:
temp = next(a)
if 'd' in temp:
#this version of above answer captures the 'f' as well
writer("output.txt", temp[temp.index('d'):temp.index('f') + 1])
except StopIteration:
break
straight forward:
### load all the data at once, fine for small files:
with open('input.txt', 'r') as f:
content = f.read().splitlines() ## use f.readlines() to have the newline chars included
### slice what you need from content:
selection = content[content.index("d"):content.index("f")]
## use content.index("f")+1 to include "f" in the output.
### write selection to output:
with open('output.txt', 'a') as f:
f.write('\n'.join(selection))
## or:
# for line in selection:
# f.write(line + '\n')

Append String to each line of .txt file in python?

I want to append some text to every line in my file
Here is my code
filepath = 'hole.txt'
with open(filepath) as fp:
line = fp.readline()
cnt = 1
while line:
#..........
#want to append text "#" in every line by reading line by line
text from .txt file
line = fp.readline()
cnt += 1
You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
Assuming you can load the full text in memory, you could open the file, split by row and for each row append the '#'. Then save :-) :
with open(filepath, 'r') as f: # load file
lines = f.read().splitlines() # read lines
with open('new_file.txt', 'w') as f:
f.write('\n'.join([line + '#' for line in lines])) # write lines with '#' appended
I'll assume the file is small enough to keep two copies of it in memory:
filepath = 'hole.txt'
with open(filepath, 'r') as f:
original_lines = f.readlines()
new_lines = [line.strip() + "#\n" for line in original_lines]
with open(filepath, 'w') as f:
f.writelines(new_lines)
First, we open the file and read all lines into a list. Then, a new list is generated by strip()ing the line terminators from each line, adding some additional text and a new line terminator after it.
Then, the last line overwrites the file with the new, modified lines.
does this help?
inputFile = "path-to-input-file/a.txt"
outputFile = "path-to-output-file/b.txt"
stringToAPpend = "#"
with open(inputFile, 'r') as inFile, open(outputFile, 'w') as outFile:
for line in inFile:
outFile.write(stringToAPpend+line)

CSV file to list of lines?

I have a txt file and I want to save each line as a list in a new file with fname as the new file name. But the output is not being saved. What am I missing?
import csv
with open('file.txt', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'w') as out:
out.write(line)
i +=1
To do what you want, you need to fix two things, one is to open the output files in "append" mode so their previous contents aren't wiped-out everytime something additional is written to them.
Secondly you need some way to know the raw data from the file for each csv row it reads. This can be difficult when you use an extension like the csv module and don't know the internals (which you shouldn't use anyway).
To work around that in this case, you can pass a custom csvfile argument to the csv.reader that will give you the information needed. Basically a small preprocessor of the data being read. Here's what I mean:
import csv
def pre_reader(file):
"""Generator that remembers last line read."""
for line in file:
pre_reader.lastline = line
yield line
with open('test_gen.csv', 'rU') as csvfile:
reader = csv.reader(pre_reader(csvfile), delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'a') as out:
out.write(pre_reader.lastline)
i +=1
Change:
with open(fname, 'w') as out:
out.write(line)
To:
with open(fname, 'a') as out:
out.write(line)
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
a Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
Better way:
import csv
with open('file.txt', 'rU') as csvfile, open(fname, 'w') as out:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
out.write(line)
You cannot write a list so change penultimate line to **out.write(str(line))**
import csv
with open('file.txt', 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter='\t')
i = 1
for line in reader:
fname = line[0] + line[1]
#print fname
with open(fname, 'w') as out:
------> out.write(str(line))
i +=1

Read and overwrite a file in Python

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()

Categories

Resources