如何使用Python从文本文件中删除回车符?

mrc*_*son 6 python unicode tab-delimited tab-delimited-text

我搜索过的东西没有用,所以我求助于专家!

我在制表符分隔的文本文件中有一些文本,其中包含某种回车符(当我在Notepad ++中打开它并使用“显示所有字符”时,在行尾看到[CR] [LF]) 。我需要删除此回车符(或其他内容),但似乎无法弄清楚。这是文本文件的片段,其中显示了带有回车符的行:

firstcolumn secondcolumn    third   fourth  fifth   sixth       seventh
moreoftheseventh        8th             9th 10th    11th    12th                    13th
Run Code Online (Sandbox Code Playgroud)

这是我试图用来替换它的代码,但是找不到返回值:

with open(infile, "r") as f:
    for line in f:
        if "\n" in line:
            line = line.replace("\n", " ")
Run Code Online (Sandbox Code Playgroud)

我的脚本只是找不到回车符。我是对这个回车做错了什么还是做出了错误的假设?我可以在文本编辑器中手动将其删除,但是文本文件中大约有5000条记录也可能包含此问题。

进一步的信息:这里的目标是从文本文件中选择两列,因此我分割了\ t字符,并将这些值作为数组的一部分来引用。它可以在没有返回值的任何行上工作,但是在有返回值的行上会失败,例如,因为这些行中没有元素9。

vals = line.split("\t")
print(vals[0] + " " + vals[9])
Run Code Online (Sandbox Code Playgroud)

因此,对于上面的文本行,此代码失败,因为该特定数组中没有索引9。对于没有[CR] [LF]的文本行,它可以按预期工作。

ins*_*get 7

根据文件类型(以及它来自的操作系统等),回车符可能是'\r''\n''\r'\n'。摆脱它们的最好方法是使用它们,无论它们是哪一种line.rstrip()

with open(infile, "r") as f:
    for line in f:
        line = line.rstrip() # strip out all tailing whitespace
Run Code Online (Sandbox Code Playgroud)

如果您只想删除回车符而不删除末尾可能存在的任何额外空格,您可以向以下提供可选参数rstrip

with open(infile, "r") as f:
    for line in f:
        line = line.rstrip('\r\n') # strip out all tailing whitespace
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助


Mic*_*ays 6

以下是如何在不使用临时文件的情况下删除回车符的方法:

with open(file_name, 'r') as file:
    content = file.read()

with open(file_name, 'w', newline='\n') as file:
    file.write(content)
Run Code Online (Sandbox Code Playgroud)


ovg*_*vin 5

Python 在所谓的 中打开文件universal newline mode,因此换行符始终是\n.

Python 通常是用通用换行符支持构建的;提供 'U' 将文件作为文本文件打开,但行可以通过以下任何一种方式终止:Unix 行尾约定 '\n'、Macintosh 约定 '\r' 或 Windows 约定 '\ r\n'。所有这些外部表示形式都被 Python 程序视为“\n”。

您逐行迭代文件。你正在更换\n队伍。但实际上没有\n,因为行已经被\n迭代器分隔并且每行不包含\n

您只需从文件中读取即可f.read()。然后替换\n进去。

with open(infile, "r") as f:
    content = f.read()
    content = content.replace('\n', ' ')
    #do something with content
Run Code Online (Sandbox Code Playgroud)


mrc*_*son 4

从技术上讲,有一个答案!

with open(filetoread, "rb") as inf:
    with open(filetowrite, "w") as fixed:
        for line in inf:
            fixed.write(line)
Run Code Online (Sandbox Code Playgroud)

显然,中的 bopen(filetoread, "rb")以这样的方式打开文件,我可以访问这些换行符并将其删除。这个答案实际上来自 Stack Overflow 网站外的用户 Kenneth Reitz。

感谢大家!