python读取文件为空,Python:为什么我在某个文本文件上的循环虽然不为空,但仍读取空行?...

本文探讨了尝试用Python打开并读取两个文件时遇到的问题,发现写入第二个文件后影响了后续从第一个文件中读取和处理的操作。作者揭示了循环遍历文件内容两次导致的冲突,并给出了正确处理多次迭代文件内容的方法。
摘要由CSDN通过智能技术生成

I was trying to learn and experiment with Python today, and I got into trying to open a text file, reading the lines from it, and then writing those lines in a 2nd text file. After that, I tried to load the lines from both files into lists, and print those lists in the console. Here is the experimental code:

f = open('D:\\origFile.txt', 'r')

f2 = open('D:\\copyFile.txt', 'w')

for line in f:

f2.write(line.rstrip() + ' ')

f2.close()

s=""

for linez in f:

s += linez

print (s)

s2=""

f2 = open('D:\\copyFile.txt', 'r+')

reading = f2.readlines()

print (reading)

for linex in f2:

s2 += linex

print (linex)

list1=s.split()

list2=s2.split()

print(list1)

print(list2)

f.close()

f2.close()

The code works as expected only when I remove or comment this part:

f2 = open('D:\\copyFile.txt', 'w')

for line in f:

f2.write(line.rstrip() + ' ')

f2.close()

Although I'm already closing f2 file after writing the contents of f1 to it. So why does it affect the rest of the file operations in the code? And how does it still affect f1? As in, the lists in the end are neither populated by the text from f1 nor f2.

Edit 1: In my question, I already tried to close the second file thinking that it would be the cause of my problem, not the loop itself; while the other question didn't even have a loop to satisfy an answer to my question. Although the answers are somewhat the same, the answer in the other question doesn't show how to use the contents of the file repeatedly without having to reset the iterator using f.seek(0) to be able to use the contents in several loops like in my code above.

解决方案

You're attempting to loop through the contents of f twice:

for line in f:

for linez in f:

... and you can't do it that way. The second loop will exit immediately, because you already read all of the lines; there are none left to read.

If you want to save the lines of a file and loop through them several times, use something like this:

all_lines = f.readlines()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值