簡體   English   中英

將新字符串添加到文本文件中特定行的末尾

[英]Adding a new string to the end of a specific line in a text file

我是python的新手,因此我無法實施我在網上找到的解決方案來解決問題。 我正在嘗試將特定字符串添加到文本文件的特定行的末尾。 據我了解的文本命令,如果我不想附加到文件末尾,則必須覆蓋該文件。 因此,我的解決方案如下:

    ans = 'test'
numdef = ['H',2] 
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
    if int(line[0]) == numdef[1]:
        if str(line[2]) == numdef[0]:
                k = ans+ line
                f.write(k)
    else:
        f.write(line)

基本上,我試圖將變量ans添加到特定行的末尾,該行出現在我的列表numdef 因此,例如,

2小時:4,0:在哪里搜索信息:谷歌

我想要

2小時:4,0:在哪里搜索信息:google測試

我也試過使用line.insert()但無濟於事。

我知道使用open命令的'a'功能在這里不是很相關且沒有幫助,但是我沒有主意。 可能會喜歡此代碼的提示,或者如果我應該廢棄它並重新考慮整個問題。 感謝您的時間和建議!

嘗試這個。 如果滿足第一個要求,但沒有另一個條件,則沒有其他情況。

ans = 'test'
numdef = ['H',2] 
f = open(textfile, 'r')
lines = f.readlines()
f.close()
f = open(textfile, 'w')
f.write('')
f.close()
f = open(textfile, 'a')
for line in lines:
    if int(line[0]) == numdef[1] and str(line[2]) == numdef[0]:
        k = line.replace('\n','')+ans
        f.write(k)
    else:
        f.write(line)
f.close()

更好的方法:

#initialize variables
ans = 'test' 
numdef = ['H',2]  
#open file in read mode, add lines into lines
with open(textfile, 'r') as f:
    lines=f.readlines() 
#open file in write mode, override everything    
with open(textfile, 'w') as f: 
    #in the list comprehension, loop through each line in lines, if both of the conditions are true, then take the line, remove all newlines, and add ans. Otherwise, remove all the newlines and don't add anything. Then combine the list into a string with newlines as separators ('\n'.join), and write this string to the file.
    f.write('\n'.join([line.replace('\n','')+ans if int(line[0]) == numdef[1] and str(line[2]) == numdef[0] else line.replace('\n','') for line in lines]))

使用方法時

lines = f.readlines()

Python自動在每行末尾添加“ \\ n”。

嘗試代替:

k =線+ ans

下列:

k = line.rstrip('\n') + ans

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM