【问题标题】:How do you delete 1st 7 lines of several *.txt files in a folder using python? [duplicate]如何使用 python 删除文件夹中多个 *.txt 文件的第一 7 行? [复制]
【发布时间】:2018-12-05 20:17:19
【问题描述】:

我有一个包含近 150 个 *.txt 文件的文件夹。我需要使用 python3.5.2 删除该文件夹中每个 .txt 文件的第一七行

【问题讨论】:

  • Python 似乎是完成任务的错误工具
  • @JackMoody 我有很多文件,没有一个文件
  • @slash 使用循环。
  • 您的文件夹结构是什么样的?您需要遍历每个文件,然后执行我给出的链接中提到的操作。
  • 所有文件的结构如下: 名称:来源:RPS:LIMP:CULP:MCL:DVS:34 345 2321 232 4564 3245 9098 我想删除从 0 到 6 的行。我正在尝试使用 os.walk。这是我的代码:

标签: python-3.x


【解决方案1】:

您可以使用 Python 的 OS Module 从您的文件夹中获取所有 *.txt 文件的名称。然后您可以遍历这些名称,从每个文件中读取所有行并用您要保留的行覆盖文件:

from os import listdir, path

path_str = '.'  # your directory path
txts = [f for f in listdir(path_str)
        if f.endswith('.txt') and path.isfile(path.join(path_str, f))]

for txt in txts:
    with open(txt, 'r') as f:
        lines = f.readlines()

    with open(txt, 'w') as f:
        f.write(''.join(lines[7:]))

【讨论】:

  • 那行得通。谢谢:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 1970-01-01
  • 2018-02-23
  • 1970-01-01
相关资源
最近更新 更多