python-3.x - 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 换行符。
解决方案
您可以在上下文中打开要读取的文件和要写入的文件,然后检查该行是否以"\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"
推荐阅读
- swiftui - 用 UIBlurEffect 填充的 SwiftUI 自定义形状
- java - JPA 存储库中的 OneToMany deleteById 方法不起作用
- javascript - Mongoose 更新子文档
- python - 如何在 Python 中以数值方式计算复杂 3D 形状的体积积分?
- ruby-on-rails - 将 Rails 项目转换为使用 Docker
- python-3.x - 熊猫按价值切片
- r - 提交作业后运行 R 代码时出错
- python - 使用 Elasticsearch,我可以为不同的匹配标记使用不同的 HTML 标签突出显示吗?
- visual-studio-code - VS Code,嵌入式语言语法高亮
- excel - 工作表更改时运行 vba 函数