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



我有一个大文本文件,它包含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( 'nn 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

点击这里查看文本文件

请帮助我。

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

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

出处:

['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')

转换很简单,您只需对 from 和 to 字符串进行str.replace。写入临时文件,以便在仍在处理该文件时不会覆盖该文件,并在完成后重命名它。

file.writelines()方法采用迭代器并反复调用它以获取要写入的行。我使用了一个生成器来读取文件的每一行并替换文本。

import os
print ("Text to search for:")
textToSearch = input( "> " ) 
print ("Text to replace it with:")
textToReplace = input( "> " )
print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
outName = fileToSearch + ".tmp"
with open(fileToSearch) as infile, open(outName, 'w') as outfile:
outfile.writelines(line.replace(textToSearch, textToReplace) for line in infile)
print("Lines replaced, do you want to overwrite original file? (y/n):")
replace = input("> ")
if replace.startswith ('y'):
os.remove(fileToSearch)
os.rename(outName, fileToSearch)
input( 'nn Press Enter to exit...' )
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()

最新更新