英文:
Having problem reading a text file in Python
问题
我正在尝试读取一个文本文件。但它没有在屏幕上打印任何内容。
这个简单的程序运行正常。
with open("This.txt",'r') as file:
for line in file:
print(line)
输出:-
Harry Potter,2
Dragon's Nest,1
Happy Life,1
但后来我在其中添加了 if else 语句。运行时,我没有得到任何输出。我的代码:-
with open("This.txt",'r') as file:
if file.read()=='':
print("File empty")
else:
for line in file:
print(line)
输出 ->
问题可能是什么?
英文:
I am trying to read a text file.
But it is not printing anything on the screen
This simple program works fine.
with open("This.txt",'r') as file:
for line in file:
print(line)
output:-
Harry Potter,2
Dragon's Nest,1
Happy Life,1
But than I added if else statement in it.
When I run it, I am not getting any output.
My code :-
with open("This.txt",'r') as file:
if file.read()=='':
print("File empty")
else:
for line in file:
print(line)
output ->
What could be the problem?
答案1
得分: 0
当你调用file.read()
时,Python会读取文件直到末尾。因此,在调用read()
函数后,当Python到达else
语句时,它会返回一个空字符串,因为它已经在文件的末尾。要让Python回到文件的开头,你需要使用file.seek(0)
。修改后的代码如下:
with open("This.txt", 'r') as file:
if file.read() == '':
print("File empty")
else:
file.seek(0) # 添加这一行
for line in file:
print(line)
英文:
When you call file.read()
, Python reads the file till the end. So, after calling the read()
function, when Python reaches the else
statement, it returns an empty string, since it is at the end of the file. To make Python go back to the start of the file, you need to use file.seek(0)
. Modified code:
with open("This.txt",'r') as file:
if file.read()=='':
print("File empty")
else:
file.seek(0) #Add this
for line in file:
print(line)
答案2
得分: 0
调用file.read()
非常浪费资源,它会将整个文件的内容读入内存,导致性能和内存使用受到严重影响,特别是当文件很大时,而你只是想测试它是否为空。
一个更高效的方法是,在逐行读取文件后调用file.tell
方法,以查看文件指针是否移动到非零位置:
with open('This.txt') as file:
for line in file:
print(line)
if not file.tell():
print('File empty')
英文:
It is extremely wasteful to call file.read()
, which reads the content of the entire file into the memory, causing a serious impact to performance and memory usage when the file is large, when all you want out of it is just to test if it is empty.
A much more efficient approach would be to call the file.tell
method after reading the file line by line to see if the file pointer moved at all to a non-zero position:
with open('This.txt') as file:
for line in file:
print(line)
if not file.tell():
print('File empty')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论