只读取文件的第一个值
Reading only the first values of a file
背景:我有一个大文件,我想从中读取前几个值。我真的不想部分读取整个文件,因为我没有进一步使用它,因此它不会使用不必要的内存并且执行速度更快(因为它不需要读取这个巨大的文件)。
来自 documentation 我正在使用:
test.txt
Greetings World :)
test.py:
with open('test.txt', buffering=3) as file:
a = file.read()
print(a)
它不仅部分读取了我的文件。
有没有办法只读取文件的一部分?
从这个答案 你会发现 buffering
实际上没有读取到一个范围。而是在 a.read()
中设置一个范围。所以:
with open('test.txt') as file:
a = file.read(3)
print(a)
returns Gre
如您所料。
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned;
如果您需要读取文本文件中的值,那么您可以使用 a.seek()
参见 seek() function?
你有几个选择。
file.read()
读取整个文件
file.read(size)
读取size数据量(文本模式为字符,二进制模式为字节)
file.readlines()
list(file)
for line in file:
都提供读取整个文件的方法
file.readline()
returns 一次一行(读取直到换行字符 (\n
) 或文件结尾 (EOF))
check here 用于文档。
背景:我有一个大文件,我想从中读取前几个值。我真的不想部分读取整个文件,因为我没有进一步使用它,因此它不会使用不必要的内存并且执行速度更快(因为它不需要读取这个巨大的文件)。
来自 documentation 我正在使用:
test.txt
Greetings World :)
test.py:
with open('test.txt', buffering=3) as file:
a = file.read()
print(a)
它不仅部分读取了我的文件。
有没有办法只读取文件的一部分?
从这个答案 buffering
实际上没有读取到一个范围。而是在 a.read()
中设置一个范围。所以:
with open('test.txt') as file:
a = file.read(3)
print(a)
returns Gre
如您所料。
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string (in text mode) or bytes object (in binary mode). size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned;
如果您需要读取文本文件中的值,那么您可以使用 a.seek()
参见 seek() function?
你有几个选择。
file.read()
读取整个文件
file.read(size)
读取size数据量(文本模式为字符,二进制模式为字节)
file.readlines()
list(file)
for line in file:
都提供读取整个文件的方法
file.readline()
returns 一次一行(读取直到换行字符 (\n
) 或文件结尾 (EOF))
check here 用于文档。