首页 > 解决方案 > Python:如果文件不以 " 结尾,则向上移动下面的行

问题描述

所以我有一个 csv 文件,它是从程序创建的报告。

该文件中包含未正确拆分的行,所有行都应以“。

我想要做的是,如果该行不以“”结尾,则脚本应将该行从下方移动到末尾缺少“”的行。

举个例子,文件的某些行如下所示:

"2019-08-12","apple", "green
", "dog", "cat", "mouse
", "rabbit"

我希望它们看起来像这样的方式如下:

"2019-08-12","apple", "green", "dog", "cat", "mouse", "rabbit"

到目前为止,我尝试的是:

with open(read_path, 'r') as open_file:
    content = open_file.read()

if not content.endswith('"'):
    content.replace('\n', '')

with open(write_path, 'w') as open_file:
    open_file.write(content)

但这并没有将行向上移动,我查看了 Notepad++ 中的 csv 文件,问题似乎是在这些行上没有 CRLF 换行符,而是 LF 换行符。

标签: python-3.xcsv

解决方案


您可以在上下文中打开要读取的文件和要写入的文件,然后检查该行是否以"\n. 如果是这样,那么您可以rstrip()在末尾删除任何空格或换行符。然后将该行写入输出文件

with open('test.dat') as data, open('output.dat','w') as output:
    for line in data:
        if not line.endswith('"\n'):
            line = line.rstrip()
        output.write(line)

测试数据

"this", "that", "something"
"2019-08-12","apple", "green
", "dog", "cat", "mouse
", "rabbit"
"hello","world"

输出.dat

"this", "that", "something"
"2019-08-12","apple", "green", "dog", "cat", "mouse", "rabbit"
"hello","world"

推荐阅读