我正在尝试将 txt 文件转换为 Python 中的 csv 文件。 txt文件的当前格式是几个字符串,中间用空格隔开。我想将每个字符串写入 csv 文件中的一个单元格。
txt文件结构如下:
UserID 桌面显示(版本)(服务器/端口句柄)、日期
UserID 桌面显示(版本)(服务器/端口句柄)、日期
等等
我的方法如下:
with open('licfile.txt', "r+") as in_file:
stripped = (line.strip() for line in in_file)
lines = (line.split(" ") for line in stripped if line)
with open('licfile.csv', 'w') as out_file:
writer = csv.writer(out_file)
writer.writerow(('user', 'desktop', 'display', 'version', 'server', 'handle', 'date'))
writer.writerows(lines)
不幸的是,这没有按预期工作。我确实得到以下 ValueError: I/O operation on closed file。此外,只有预期的行标题显示在 csv 文件的一个单元格中。
关于如何进行的任何提示?非常感谢。
最佳答案
怎么样
with open('licfile.txt', 'r') as in_file, open('licfile.csv', 'w') as out_file:
for line in in_file:
if line.strip():
out_file.write(line.strip().replace(' ', ',') + '\n')
对于德国的 Excel 爱好者...
...
...
...
... .replace(' ', ';') + '\n')
:)
关于python - 如何在 Python 中格式化 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58010348/