如何通过 python 将 : 字符转换为文件中的换行符

How to convert the : char into a newline in a file by python

我有一个文本文件,其中的数据格式如下:

格式化前:

a1 ,a2,a3:b1 ,b2,b3:c1 ,c2,c3:....so on. 

现在我想以这种特定形式转换数据:

格式化后:

a1,a2,a3
b1,b2,b3
c1,c2,c3
...so on

要做的事情:首先我想转换 'newline' 中的 : 字符,并希望在每个第一个字符(例如 a1 b1 c1 之后恢复 space。 space 造成问题,因为格式化后的数据要转换为 csv 文件。

我尝试将一个字符一个字符从一个文件传输到另一个文件,其中我使用 if 大小写将 : 替换为 'newline'。 对于换行符,我使用了这个 \n

file.txt 是包含 a1 ,a2,a3:b1 ,b2,b3:c1 ,c2,c3:....so on

的文件

convert.txt 如果我想要格式化数据的文件

with open('file.txt','r') as rf:
    with open('convert.txt','w') as wf:
        a=1
        rf_temp = rf.read(a)
        while len(rf_temp) > 0:
            if rf_temp == ':':
                rf_temp.replace(':','\n')
            wf.write(rf_temp)
            rf_temp = rf.read(a)
    wf.close()
rf.close

数据被清楚地复制,但不是我想要的格式,包括“:”这个符号。 复制没有问题

str.joinstr.split

结合使用

例如:

print("\n".join("a1 ,a2,a3:b1 ,b2,b3:c1 ,c2,c3".split(":")))

输出:

a1 ,a2,a3
b1 ,b2,b3
c1 ,c2,c3
# define the input file and output file
inputFile = 'test.txt'
outFile = "test.csv"

# read data from input file
data = open(inputFile).read()

# change data to wanted format, using '\n' to replace ':'
data = "\n".join(data.split(':'))

# save the changed data to output file
outF = open(outFile, 'w')
outF.write(data)

print(data)

输出

a1 ,a2,a3
b1 ,b2,b3
c1 ,c2,c3
a = "a1 ,a2,a3:b1 ,b2,b3:c1 ,c2,c3"
b = a.split(":")
for i in b:
    print(i)

如果您需要一行解决方案,您可以通过以下方式完成

print("\n".join(a.split(":")))