简体   繁体   English

在python中读取.txt文件

[英]Reading a .txt file in python

I have use the following code to read a .txt file: 我已使用以下代码读取.txt文件:

f = os.open(os.path.join(self.dirname, self.filename), os.O_RDONLY)

And when I want to output the content I use this: 当我想输出内容时,我使用以下代码:

os.read(f, 10);

Which means that this method reads 10 bytes from the beginning of the file on. 这意味着此方法从文件开头读取10个字节。 While I need to read the content as much as it is, using some values such as -1 and so. 虽然我需要尽可能多地阅读内容,但是使用一些值,例如-1等。 What should I do? 我该怎么办?

You have two options: 您有两种选择:

  1. Call os.read() repeatedly. 重复调用os.read()

  2. Open the file using the open() built-in (as opposed to os.open() ), and just call f.read() with no arguments. 使用内置的open() (而不是os.open() )打开文件,然后仅调用不带参数的f.read()

The second approach carries certain risk, in that you might run into memory issues if the file is very large. 第二种方法具有一定的风险,如果文件很大,您可能会遇到内存问题。

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

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