简体   繁体   English

如何将已经打开的文件转换为字符串?

[英]How to convert an already open file to string?

Given an open file, return the contents as a string.( This assumes the autotester test the function with a random file so the variable should be open to multiple files of the same type) 给定一个打开的文件,将其内容作为字符串返回。(这假定自动测试器使用一个随机文件来测试该函数,因此该变量应该对多个相同类型的文件开放)

def read_file(myfile):
'''(file) -> str
Read the open file and return as a string.'''
def read_file(myfile):
    return myfile.read()
content = myfile.read()

Or to read it line by line and put it in a list: 或者逐行阅读并将其放在列表中:

content_list = myfile.readlines()

You can then use: 然后,您可以使用:

content_list = [x.strip() for x in content_list]

to remove \\n characters. 删除\\ n个字符。

打开文件后(我建议使用with语句,例如with open(filename.txt, "r") as file ,使用fileString = file.read()fileString将成为内容

To deal with larger files, it's a good idea to read in chunks of fixed size. 要处理较大的文件,最好读取固定大小的块。 If you try to open an image, for example, and don't use buffered reading, you'll get a MemoryError . 例如,如果您尝试打开图像,并且不使用缓冲读取,则会收到MemoryError

def read_file(filename):
    BUFFER_SIZE = 65536
    contents = []
    with open(filename, "r") as f:
        while True:
            chunk = filename.read(BUFFER_SIZE)
            if not chunk:
                break
            contents.append(chunk)
    return "".join(contents)

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

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