使用python拆分并保存文件中的文本
下面是输入文件sample_text.txt使用python拆分并保存文件中的文本,python,Python,下面是输入文件sample_text.txt 10001ScottTiher100040 10002ScoteTijer100042 10003ScotrTieer100043 10004ScotfTiler100044 10005ScotyTiper100046 10006ScotlTioer100047 10007ScotiTiwer100049 我需要保存在同一个文件如下,你能帮我这个 10001,Scott,Tiher,100040 10002,Scote,Tijer,100042 1
10001ScottTiher100040
10002ScoteTijer100042
10003ScotrTieer100043
10004ScotfTiler100044
10005ScotyTiper100046
10006ScotlTioer100047
10007ScotiTiwer100049
我需要保存在同一个文件如下,你能帮我这个
10001,Scott,Tiher,100040
10002,Scote,Tijer,100042
10003,Scotr,Tieer,100043
10004,Scotf,Tiler,100044
10005,Scoty,Tiper,100046
10006,Scotl,Tioer,100047
10007,Scoti,Tiwer,100049
我尝试了下面的代码,但无法将b保存在新文件或同一文件中
with open('D:\Programs\python\sql_test.txt','r+') as f:
for line in f:
for word in line.split():
b = str(word[0:5])+ ',' + str(word[5:10]) + ',' + str(word[10:15])+','+ str(word[15:21])
print(b)
您必须使用
f.write(b)
将b
保存到文件中这是一种方法
演示:
res = []
with open(filename, "r") as infile:
for i in infile.readlines():
val = i.strip()
res.append([val[:5], val[5:10], val[10:15], val[15:]])
with open(filename, "w") as outfile:
for i in res:
outfile.write(", ".join(i) + "\n")
您可以使用
上下文管理器打开两个文件:一个用于输入,另一个用于输出
with open("ifilename", 'r') as ifile, open("ofilename", 'w') as ofile:
for line in ifile:
print(','.join([line[0:5], line[5:10], line[10:15], line[15:]]), file=ofile)
也许reg
很容易做到这一点:
import re
with open("origin.txt", 'r') as in_fd, open("new.txt", 'w') as out_fd:
for line in in_fd.readlines():
match = re.match(r"([0-9]+)([a-z]+)([0-9]+)", line, re.I)
out_fd.write(','.join(match.groups())+ '\n')
迟交的答复
没有第二个循环,您的早期解决方案会更好
正如您所知,您不能拥有一个带有读取选项(r
)和写入选项(w
)的文件
选项r+
,将转换后的数据附加到文件末尾。为了练习,我们将不使用r+
在这里,我们使用f读取文件,使用f1写入结果,并以一个格式结尾,其中使用a\n
跳行
In [3]: with open('split.txt','r') as f, open('split2.txt','w') as f1: #one file for read and the other one for saving the result
...: for line in f:
...: output = str(line[0:5])+ ',' + str(line[5:10]) + ',' + str(line[10:15])+','+ str(line[15:21])
...: f1.write("{0}{1}".format(output,"\n")) #outputting with \n to jump to the next line for any new line
你查过如何写入文件了吗?你似乎能够创建你想要的字符串,所以。。。