python - 如何在 .txt 文件中的所有字符之间添加空格

标签 python python-2.7 whitespace

在 Python 2.7 中,我想知道如何在 .txt 文件(非常大的文件)中的每个字符之间添加一个空格。我知道如何使用 Emacs 执行此操作,但速度很慢。

输入示例:

122212121212121
212121212121212
121212121212121

预期输出:

1 2 2 2 1 2 1 2 1 2 1 2 1 2 1
2 1 2 1 2 1 2 1 2 1 2 1 2 1 2
1 2 1 2 1 2 1 2 1 2 1 2 1 2 1

最佳答案

试试这个:

with open(infile) as open_file:
    with open(outfile, 'w') as write_file:
        for line in open_file:
            write_file.write(" ".join(line))

关于python - 如何在 .txt 文件中的所有字符之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35751290/

相关文章:

bash - 在 $variable 后面添加一个逗号

Python pydantic 验证日期

python - 忽略条件的后续实例(for 循环和 if 语句)

html - 容器和导航栏之间的奇怪空间

Python pandas 替换

python-2.7 - 如何在 PyQt4 中更改 QTextEdit 中所有内容的字体大小?

c++ - 长构造函数初始化列表

Python 内部函数变量作用域

python - 稀疏矩阵的高效最近邻搜索

python - 在同一个图表中绘制背景和标签-matplotlib