【问题标题】:Python script to strip new lines from .txt files contained in a directory用于从目录中包含的 .txt 文件中删除新行的 Python 脚本
【发布时间】:2016-11-18 15:08:38
【问题描述】:

我有一个目录中包含的 .txt 文件列表。每个文件可能有多行。从该目录中包含的所有文件中删除所有换行符的 Python 脚本可能是什么?生成的文件应该只有一行包含所有文本。

import os
os.chdir("/home/Pavyel/Desktop/Python Programs")

for i in os.listdir(os.getcwd()):
    if i.endswith(".txt") :
    f = open(i)
    contents = f.read()
    new_contents = contents.replace('\n', '')
    print i
    continue
else:
    continue

【问题讨论】:

  • 可能有很多脚本...你试过写一个了吗?
  • import os os.chdir("/home/iitp/Desktop/Python Programs") for i in os.listdir(os.getcwd()): if i.endswith(".txt") : f = open(i) contents = f.read() new_contents = contents.replace('\n', '') print i continue else: continue

标签: python python-3.x


【解决方案1】:
import os
import sys
import fileinput

dir = "." #Directory to scan for files

file_list = os.listdir(dir)

for file in file_list:
    if file.endswith(".txt"):
        with fileinput.FileInput(file, inplace=True, backup=".bak") as f:
            for line in f:
                sys.stdout.write(line.replace("\n", ""))

这还将创建它编辑的所有文件的备份,以防万一。
如果您不想备份,请从 7 日删除 , backup=".bak"

【讨论】:

  • 这一行的问题:print(line.replace("\n", ""), end="")
  • @Pavyel 正在运行不兼容的 Python 版本。很可能是 Python 2,因为它不支持新的打印功能。该脚本在我的计算机上运行良好。无论如何,我已经更改了代码,因此它适用于更多 Python 版本。
【解决方案2】:

使用glob.glob() 查找感兴趣的文件,即以.txt 结尾的文件。 glob() 返回匹配文件名的列表,并保持路径不变,因此您无需更改目录。

fileinput.input()处理文件:

import fileinput
from glob import glob

pattern = '/home/Pavyel/Desktop/Python Programs/*.txt'
files = glob(pattern)
if files:
    with fileinput.input(files, inplace=True) as f:
        for line in f:
            print(line.rstrip('\n'), end='')

如果您使用的是 Python 2,可能值得将 mode='U' 传递给 fileinput.input() 以确保启用通用换行符处理,这是 Python 3 的默认设置。启用该功能后,您可以确定 \n 将无论您的代码在哪个平台上运行,都匹配换行符。

【讨论】:

    猜你喜欢
    • 2021-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2021-10-28
    • 2023-01-04
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    相关资源
    最近更新 更多