gpt4 book ai didi

python文件读取

转载 作者:行者123 更新时间:2023-11-28 20:29:06 25 4
gpt4 key购买 nike

def file_open(filename):
fo=open(filename,'r')
#fo.seek(5)
fo.read(3)
fo.close()

file_open("file_ro.py")

我希望上面的程序从文件中返回前 3 个字节。但它什么也没返回。当我在交互式 python 命令提示符下运行它们时 - 我得到了预期的输出!

最佳答案

虽然您自己的答案打印读取的字节,但它不会返回它们,因此您将无法在其他地方使用结果。此外,还有一些其他改进的余地:

  • file_open 不是该函数的好名称,因为它从文件中读取并返回字节,而不是仅仅打开文件。
  • 即使 fo.read(3) 失败,您也应该确保关闭文件。您可以使用 the with statement来解决这个问题。

修改后的代码看起来像这样:

def read_first_bytes(filename):
with open(filename,'r') as f:
return f.read(3)

用法:

>>> print read_first_bytes("file.py")

关于python文件读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3211031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com