如何将字符串值与文本文件Python中的每一行连接起来

时间:2018-05-10 04:30:35

标签: python python-3.x python-2.7 concatenation string-concatenation

我有一个大文本文件,它包含700k行。 我想连接或在每一行附加小字符串“/products/all.atom”。

我试过这段代码

enter code here
import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " ) 

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
if textToSearch in line :
    print('Match Found')
else:
    print('Match Not Found!!')
tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )

但是代码不是很完美,我在这里做的是将“.com”替换为“.com / products / all.atom”,但是当我运行这个命令时,循环是无限的,它会写入10GB大小的文件

这是我想要的例子:

store1.com > store1.com/products/all.atom
store2.com > store2.com/products/all.atom
store3.com > store3.com/products/all.atom

click here to check text file

请帮帮我。

2 个答案:

答案 0 :(得分:0)

fo=open('sta.txt','r+') # open file for read    
lines=fo.read() # reading lines in file 
fo.close()  
fo=open('sta.txt','w') # open file for Write    
for i in lines.split('\n')[:-1]:  #split the lines (using \n)and avoid last one
    fo.write(i+' hai \n') # write new lines #replace 'hai with what you need to append
fo.close()

答案 1 :(得分:0)

尝试列表理解和字符串连接:

with open('file.txt','r') as f:
    print([line.strip() + "/products/all.atom" for line in f])

outout:

['store1.com/products/all.atom', 'store2.com/products/all.atom', 'store3.com/products/all.atom', 'store4.com/products/all.atom']

更新了解决方案:

以下是您在新文件中的写作方式:

with open('names','r') as f:
    data=[line.strip() + "/products/all.atom" for line in f]
    with open('new_file','w+') as write_f:
        for line_1 in data:
            write_f.write(line_1 + '\n')