python - 如何在单元格中将txt文件转换为csv文件
问题描述
我正在尝试将 txt 文件转换为以下格式:
NOTE
Date : 2/12/2019
Name : SomeName
Amount : 9000.0
Total : 59000.0
3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
对于 csv 文件,省略NOTE
并采用单元格格式:
Date,Name,Amount,Total,Signature
2/12/2019, SomeName,9000,59000,3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
到目前为止,我存档要做的是:
Date,Number,Amount,Total,Signature
['NOTE'],"['Date', '2/12/2019']","['Name', 'SomeName']","['Amount', '9000.0']","['Total', '59000.0']",['3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx']
这是我的代码:
with open('example.txt', 'r') as in_file:
stripped = [line.replace(":","").split() for line in in_file]
zipped = zip([stripped]*1)
with open('out_file.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('Date', 'Number', 'Amount', 'Total', 'Signature'))
for group in zipped:
writer.writerows(group)
解决方案
Question: to convert a txt file to csv file in cells
Example using csv.DictWriter
.
import io, csv
TXT = """NOTE
Date : 2/12/2019
Name : SomeName
Amount : 9000.0
Total : 59000.0
3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
NOTE
Date : 2/12/2019
Name : SomeName
Amount : 9000.0
Total : 59000.0
3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
"""
with io.StringIO(TXT) as in_file,\
io.StringIO() as out_file:
fieldnames = ['Date', 'Name', 'Amount', 'Total', 'Signature']
writer = csv.DictWriter(out_file, fieldnames=fieldnames)
writer.writeheader()
while True:
data = {}
for row in range(6):
try:
line = next(in_file)
s = line.rstrip().split(':')
if len(s) == 2:
data[s[0].strip()] = s[1].strip()
else:
data['Signature'] = s[0]
except StopIteration:
break
if data:
writer.writerow(data)
else:
break
print('{}'.format(out_file.getvalue()))
Output:
Date,Name,Amount,Total,Signature 2/12/2019,SomeName,9000.0,59000.0,3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx 2/12/2019,SomeName,9000.0,59000.0,3ABA2363F5305877265757265784B2EB94ABxxxxxxxxxxxxxxxx
推荐阅读
- gremlin - 从顶点列表创建新的遍历对象
- reactjs - 生产模式:React 中的 minificator 会更改组件功能的名称吗?
- delay - 管道 Gstreamer RTSP 文件下沉有很大延迟
- docker - nginx: [emerg] open() "/var/run/nginx.pid" 失败 (13: Permission denied)
- java - 如何通过计算两个不同的数组数据对数据进行排序。使用集合
- java - IntelliJ 不显示私有或公共图标,也就是方法的可见性图标
- c++ - 函数末尾的 && 是什么意思
- javascript - 如何在 XPage 中存储 IBM Notes 数据库对象变量并稍后访问它
- ios - 故事板减少视图之间的差距
- autoconf - 为什么 pkg-config 从 i686-w64-mingw32-pkg-config 列出不同的可用软件包?