简体   繁体   English

使用python分割文本并将其保存在文件中

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

Below is the input file sample_text.txt 下面是输入文件sample_text.txt

10001ScottTiher100040
10002ScoteTijer100042
10003ScotrTieer100043
10004ScotfTiler100044
10005ScotyTiper100046
10006ScotlTioer100047
10007ScotiTiwer100049

I need to save this in the same file as below, can you please help me on this.... 我需要将此文件保存在以下相同的文件中,请您对此提供帮助。

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

I have tried the below code, but unable to save the b in new file or same file 我尝试了以下代码,但无法将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)

You can open two file with with context manager: One for input, The other for output. 您可以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)

This is one approach 这是一种方法

Demo: 演示:

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

Maybe the reg is simple to do this: 也许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保存到文件中

Very late answer 答案很晚

Your early solution is better without the second loop. 没有第二个循环,您的早期解决方案会更好。

As you know, you cannot have a file with the read option ( r ) and also the write ( w ) option. 如您所知,您不能拥有带有读取选项( r )和写入( w )选项的文件。

The option r+ , append the transformed data to the end of the file. 选项r+ ,将转换后的数据附加到文件末尾。 For the sake of the exercice, we will not use r+ 为了锻炼,我们将不使用r+

Here, we use f to read the file and f1 to write the results, ending with a formatting with a \\n to jump lines. 在这里,我们使用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