python文件读取

web*_*org 2 python file

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

file_open("file_ro.py")
Run Code Online (Sandbox Code Playgroud)

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

Pär*_*der 7

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

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

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

def read_first_bytes(filename):
    with open(filename,'r') as f:
        return f.read(3)
Run Code Online (Sandbox Code Playgroud)

用法:

>>> print read_first_bytes("file.py")
Run Code Online (Sandbox Code Playgroud)