[英]Reading text from a file, then writing to another file with repetitions in text marked
[英]reading a text file, then writing to another text without a user input word
我需要幫助閱讀文本文件以搜索用戶輸入的單詞,然后將該文本文件中的數據復制到另一個沒有用戶輸入單詞的文本文件。
def remove(infile, outfile, target):
for line in infile:
for word in line.split():
if word != target:
outfile.write(word)
def main():
outfile = open('outputFile.txt', 'w')
infile = open('inputFile.txt', 'r')
#Ask user for word they would like to omit from outfile
target = input("What word would you like to delete from input file?: ")
remove(infile, outfile, target)
infile.close()
outfile.close()
main()
上面的代碼可以正常工作。 它在第一個文本文件中搜索用戶輸入的單詞並寫入一個新文件,但它沒有以適當的間距寫出。 它都在一行上,沒有任何空格。 如何使用與原始文檔相同的空格和 \n 寫入新文件?
def remove(infile, outfile, target):
for line in infile:
for word in line.split(' '):
if word != target:
outfile.write(word+' ') # You forgot to add the space that was removed while splitting the line.
outfile.write('\n') # you also forgot to add the newline
def main():
outfile = open('outputFile.txt', 'w')
infile = open('inputFile.txt', 'r')
#Ask user for word they would like to omit from outfile
target = input("What word would you like to delete from input file?: ")
remove(infile, outfile, target)
infile.close()
outfile.close()
main()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.