【问题标题】:Reading and Writing from files in python [closed]在python中读取和写入文件[关闭]
【发布时间】:2016-02-19 13:17:24
【问题描述】:

我在 python 中创建了一个文本文件,我正在努力找出如何从 python 中的文本文件中打印某些行。希望可以有人帮帮我。我知道这与 f.write 或 f.read 有关。

【问题讨论】:

标签: python file


【解决方案1】:

你可以试试这样的:

f = open("C:/file.txt", "r")  #name of file open in read mode

lines = f.readlines()   #split file into lines

print(lines[1])  #print line 2 from file

【讨论】:

  • 感谢您的帮助
【解决方案2】:
with open('data.txt') as file_data:
     text = file_data.read()

如果您使用 *.json 文件,好的解决方案是:

data = json.loads(open('data.json').read()))

【讨论】:

    【解决方案3】:

    使用with关键字在打开文件后自动处理文件关闭。

    with open("file.txt", "r") as f:
        for line in f.readlines():
            print line #you can do whatever you want with the line here
    

    即使您的程序在执行期间中断,它也会处理文件关闭。另一种手动方式是:

    f = open("file.txt", "r")
    for line in f:
        print line
    f.close()
    

    但请注意,仅在执行循环后才会在此处关闭。另请参阅此答案Link

    【讨论】:

      猜你喜欢
      • 2013-08-09
      • 2012-11-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多