Only the first line of output is printed in my text file
I have a text file that I was reading, and then I extract the data I want and try to send it to another new text file, but only the first line ends up in the new text file.
import csv
f = open('C:\\Users\\c\\Documents\\DCX.txt')
next(f)
csv_f=csv.reader(f, delimiter='\t')
for row in csv_f:
if 'DCX3520E' in row[0] and 'NULL' not in row[6]:
with open("out.txt","w") as f1:
dcx = row[0] + " " + row[6]
aa = dcx[9:]
print(aa)
f1.writelines(aa)
source to share
The biggest problem I see is if you open your file in write mode in a for loop. Every time you open a file in write mode, you clear the file and delete everything in it.
Two transparent solutions:
- Make the string
with
an external context - Open in append ('a') instead.
Since it seems like you are approaching this issue the first time, I am going to deliberately avoid posting a complete solution. I think it's important that you understand what's going on here and try to fix it yourself.
source to share
The call open("out.txt","w")
opens the file in overwrite mode. Here you can use open("out.txt","a")
to add, but only if you have a good reason to reopen the file every time. Also, it is best to open the file, write to it many times, and then close it i.e.
with open("out.txt","w") as out_file:
for row in csv_f:
if 'DCX3520E' in row[0] and 'NULL' not in row[6]:
dcx = row[0] + " " + row[6]
aa = dcx[9:]
print(aa)
out_file.writelines(aa)
source to share