【问题标题】:How can I read a txt file using python [closed]如何使用 python 读取 txt 文件 [关闭]
【发布时间】:2022-01-09 19:00:54
【问题描述】:

data.txt

我想用 python 读取这个文件。

【问题讨论】:

    标签: python file txt


    【解决方案1】:
    f = open('path/to/file.txt')
    content = f.read()
    f.close()
    

    【讨论】:

      【解决方案2】:

      写入文件

      file1 = open('data.txt', 'w')
      file1.writelines("hello world")
      file1.close()
      

      读取文件

      file1 = open('data.txt', 'r')
      Lines = file1.readlines()
      

      如果你不明白,请随时问我一个问题。

      【讨论】:

        【解决方案3】:

        下面的 with 装饰器会在完成后自动关闭文件。

        with open("data.txt", encoding='utf-8') as file:
            my_data = file.read()
        

        如果使用运行时,请确保在第二行之前包含四个空格,然后再按一次 Enter 结束 with 语句,然后键入 my_data 确认变量包含文件中的文本。

        您的会话将如下所示:

        >>> with open("data.txt", encoding='utf-8') as file:
        ...     my_data = file.read()
        ... 
        >>> my_data               
        'This is the text in the file'
        

        【讨论】:

          【解决方案4】:

          使用with open() as,如下所示

          _file = 'temp.txt'
          
          with open(_file, 'r') as fyl:
              ct = fyl.read()
          
          #do something
          

          这还有一个额外的好处,即即使发生异常也会关闭文件,因此最好使用with open() as

          【讨论】:

            猜你喜欢
            • 2011-04-13
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-09-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-04-07
            相关资源
            最近更新 更多