[英]only first line of output gets printed to my 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)
如果您在for循環中以寫入模式打開文件,我可以看到最大的問題。 每次在寫入模式下打開文件時,都會清空文件並刪除當前所有文件。
兩個明確的解決方案如下:
with
線條成為最外層的背景 因為你第一次看到你正在接近這個問題,所以我會故意避免發布完整的解決方案。 我認為重要的是你要了解這里發生了什么,並嘗試自己修復它。
調用open("out.txt","w")
以覆蓋模式打開文件。 在這里你可能想要使用open("out.txt","a")
來追加,但open("out.txt","a")
是你有充分的理由每次都重新打開文件。 除此之外,最好的做法是打開文件,多次寫入,然后關閉它,即
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)
不要在for循環中打開文件。 這會每次都覆蓋文件。
with open("out.txt","w") as f1:
for row in csv_f:
if 'DCX3520E' in row[0] and 'NULL' not in row[6]:
dcx = row[0] + " " + row[6]
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.