【问题标题】:How do get Python to print the contents of a file [duplicate]如何让Python打印文件的内容[重复]
【发布时间】:2013-08-19 22:45:48
【问题描述】:

我正在尝试让 Python 打印文件的内容:

log = open("/path/to/my/file.txt", "r")
print str(log)

给我输出:

<open file '/path/to/my/file.txt', mode 'r' at 0x7fd37f969390>

而不是打印文件。该文件中只有一个短字符串,当我执行相反的操作时(将我的 Python 脚本中的 user_input 写入同一个文件),它可以正常工作。

edit:我知道 Python 认为我在问什么,我只是想知道从文件中打印内容的命令是什么。

【问题讨论】:

标签: python linux bash


【解决方案1】:

open 为您提供了一个不会一次自动加载整个文件的迭代器。它逐行迭代,因此您可以像这样编写循环:

for line in log:
    print(line)

如果您只想将文件内容打印到屏幕上,您可以使用print(log.read())

【讨论】:

    【解决方案2】:

    最好用“with”来自动关闭描述符。这适用于 2.7 和 python 3。

    with open('/path/to/my/file.txt', 'r') as f:
        print(f.read())
    

    【讨论】:

      【解决方案3】:

      open() 实际上会打开一个file object 供您阅读。如果您打算将文件的完整内容读入日志变量,那么您应该使用read()

      log = open("/path/to/my/file.txt", "r").read()
      print log
      

      这将打印出文件的内容。

      【讨论】:

        【解决方案4】:
        file_o=open("/path/to/my/file.txt")   //creates an object file_o to access the file
        content=file_o.read()                 //file is read using the created object
        print(content)                        //print-out the contents of file
        file_o.close()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-08-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多