使用python创建修改的txt文件

2024-06-18 14:58:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何修改文本文件。假设我有.txt之类的文件

1, yes, cool being
how, are you doing
see, you, you see them

我想创建一个新的/修改过的文件,其中

1
yes, cool being

how
are you doing 

see
you, you see them

我尝试了以下代码

wordlist = []
with open('scores.txt') as f:
    wordlist = [line.split(None, 1)[0] for line in f]
    print(wordlist[0]) # trying to see if the output was the way i wanted

Tags: 文件thetxtyoulineareyeshow
3条回答

因此,您希望在第一次出现,split,并与一个换行符(\n)合并,然后再次将“段落”与一个换行符合并

wordlist = []
with open('scores.txt', 'r+') as f:
    origlist = ['\n'.join(line.split(',', 1)) for line in f]

    wordlist.append('\n'.join(origlist))
    print(wordlist[0])
    f.write(wordlist[0])  # write back to scores.txt file

产生

'1\n yes, cool being\n\nhow\n are you doing\n\nsee\n you, you see them'

(此解决方案建议不会按照您的要求在字符串末尾追加换行符。如果您正在运行windows,请将\n替换为\r\n,在MAC上,将\r替换为。)

with open('scores.txt') as f:
    lines = f.readlines()
    for line in lines:
        splited = line.split(', ') # Split
        first_word = splited[0]
        others = ', '.join(splited[1:]) # Put them back
        print (first_word)
        print (others)
        print () # Empty line

尝试:

file_in = open("input.txt","r")
file_out = open("output.txt","a")
line = file_in.readline()
while(line):
    file_out.write(line[0:line.index(',')]+"\n"+line[line.index(',')+1::]+"\n\n")
    line=file_in.readline()
file_in.close()
file_out.close()

相关问题 更多 >