python - 如何在 Python 中格式化 txt 文件

标签 python python-3.x csv formatting format

我正在尝试将 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/

相关文章:

python - 如何测量生成器序列的长度(list comp vs generator expression)

python - 尝试模拟 Counter,收到 TypeError : 'str' object is not callable

python - 如何在神社中循环每个唯一变量?

python-3.x - 在 Python 中创建路径长度超过 260 个字符的目录

python - 从 C++ 调用 Python 脚本并使用其输出

python - 创建一个从文件读取的函数,创建一个附加到列表的对象

node.js - 在 node.js 中读取 csv 文件的内容

python - 如何删除部分项目并替换循环中的列表元素?

java将列表字符串写入csv文件

c++ - 使用高斯消元的文本文件的逆矩阵。 C++