简体   繁体   English

Python逗号分隔文本文件

[英]Python comma delimiting a text file

I am learning python at the moment and I have a text file with lots of numbers separated by a newline (\\n) like: 我目前正在学习python,我有一个文本文件,其中包含许多用换行符(\\ n)分隔的数字:

5 100 7 83 5 100 7 83

What's the easiest way to read/write into a new text file putting the numbers into a comma delimited format like: 读取/写入新文本文件的最简单方法是将数字转换为以逗号分隔的格式,例如:

5, 100, 7, 83 5、100、7、83

看一下csv模块 ,该模块旨在读取和写入此类格式。

For each line in the file, you want to split it apart on spaces and rejoin it with commas: 对于文件中的每一行,您都希望将其在空格处分开并用逗号重新连接:

with open('infile.txt') as infile, open('outfile.txt', 'w') as outfile:
    outfile.write(', '.join(infile.read().split('\n')) + '\n')

You could also look at the csv module, if you want to do anything more complicated. 如果您想做任何更复杂的事情,也可以看看csv模块。

The very simplest way, especially if the file is not very big 最简单的方法,尤其是在文件不是很大的情况下

with open('infile.txt') as infile, open('outfile.txt', 'w') as outfile:
    outfile.write(infile.read().replace(" ", ", "))

csv module is overkill if you are just dealing with numbers that don't need special treatment or escaping 如果您只需要处理不需要特殊处理或转义的数字,则csv模块就显得过高了

If the file is too large to read into memory at once, use something like Abe's answer 如果文件太大而无法一次读入内存,请使用类似安倍晋三的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM