简体   繁体   English

为什么不从文件中打印单行?

[英]Why won't a single line print from a file?

As part of a bigger project, I would simply like to make sure that a file can be opened and Python can read and use it. 作为更大项目的一部分,我只想确保可以打开一个文件,并且Python可以读取和使用它。 So after I opened up the txt file, I said: 因此,在打开txt文件后,我说:

data = txtfile.read()

first_line = data.split('\n',1)[2]

print(first_line)

I also tried 我也试过

print(f1.readline())

where f1 is the txt file. 其中f1是txt文件。 This, again, did nothing. 再次,这什么也没做。 I am using the spyder IDE, and it just says running file, and doesn't print anything. 我使用的是spyder IDE,它只显示正在运行的文件,不打印任何内容。 Is it because my file is too large? 是因为我的文件太大吗? It is 4.6 gigs. 是4.6场演出。

Does anyone have any idea what's going on? 有人知道发生了什么吗?

and it just says running file, and doesn't print anything. 它只是说正在运行文件,什么都不打印。 Is it because my file is too large? 是因为我的文件太大吗? It is 4.6 gigs. 是4.6场演出。

Yes. 是。

data = txtfile.read()

This function is going to read the entire file. 此功能将读取整个文件。 Since you stated that the file is 4.6GB, it is going to take time to load the entire file and then split the by newline character. 由于您说的文件是4.6GB,因此加载整个文件,然后用换行符分隔,将需要一些时间。

See this: Read large text files in Python 查看此内容: 使用Python读取大型文本文件

I don't know your context of use, so, if you can process line by line, it would be simpler. 我不知道您的使用环境,因此,如果您可以逐行处理,它将更加简单。 Or even chunks would make it simpler than reading the entire file. 甚至块都比读取整个文件更简单。

This should work: 这应该工作:

with open('file-name') as f:
    print(f.readline())
first_line =  open('myfile.txt', 'r').readline()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM