gpt4 book ai didi

python - 使用 python 在文件中拆分和保存文本

转载 作者:行者123 更新时间:2023-11-28 22:18:40 25 4
gpt4 key购买 nike

下面是输入文件sample_text.txt

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)

最佳答案

您可以使用 with 上下文管理器打开两个文件:一个用于输入,另一个用于输出。

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)

关于python - 使用 python 在文件中拆分和保存文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50304216/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com