簡體   English   中英

使用python分割文本並將其保存在文件中

[英]To split and save text in a file using python

下面是輸入文件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)

這是一種方法

演示:

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")

也許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')

您必須使用f.write(b)b保存到文件中

答案很晚

沒有第二個循環,您的早期解決方案會更好。

如您所知,您不能擁有帶有讀取選項( r )和寫入( w )選項的文件。

選項r+ ,將轉換后的數據附加到文件末尾。 為了鍛煉,我們將不使用r+

在這里,我們使用f讀取文件,並使用f1寫入結果,最后以\\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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM