python中的文件到数组

2024-04-26 02:23:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读一本关于python的教程,这本教程是为非常初学者准备的,在某个时候作者定义了一些处理文件的方法。我的疑问与内存管理和文件数组有关。你知道吗

#open a file for reading
file = open(filename, 'r')
#this turns the file into an array. 
lines = file.readlines() `

Python是否聪明到可以检查文件大小?如果文件有大约1GB的数据会发生什么?Python会将整个文件抛出到内存(数组)中吗?或者这是一个懒惰操作EEE>,就像C/C++一样!你知道吗

提前谢谢。你知道吗


Tags: 文件方法内存for定义教程作者数组
2条回答

引用Python Tutorial

To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").

它也适用于readlines(),因此Python将把整个文件“抛出”到内存中。你知道吗

另外,通过引用Python Docs

file.readlines([sizehint]): Read until EOF using readline() and return a list containing the lines thus read. ...

Python is smart enough to check the file size?

是的。有一些操作系统相关的功能。您可以使用它们获得文件大小。你知道吗

What happens if the file has about 1 GB of data? Python will throw the entire file to the memory (array)? Or this is a lazy operation, just like C/C++ does!

如果您使用fp.readlines,那么1GB的数据将存储在内存中。 但毫不奇怪,有这样一个函数,它增加了文件指针,如C/C++。因此,您可以逐块读取数据并减少内存使用。你知道吗

fp.read(n)

我认为这是你所说的C/C++文件操作。你知道吗

相关问题 更多 >

    热门问题