How do I edit a text file in Python?

前端 未结 4 1471
小鲜肉
小鲜肉 2021-02-06 17:50
text = open(\'samiam.txt\', \'r+\')
keyword = \" i \"
keyword2 = \"-i-\"
replacement = \" I \"
replacement2 = \"-I-\"

for line in text:    
    if keyword in line:
             


        
4条回答
  •  伪装坚强ぢ
    2021-02-06 18:39

    In your code just replace the line

    for line in text:
    

    with

    for line in text.readlines():
    

    Note that here I am assuming that the you are trying to add the output at the end of the file. Once you have read the entire file, the file pointer is at the end of the file (even if you opened the file in r+ mode). Thus doing a write will actually write to the end of the file, after the current contents.

    You can examine the file pointer by embedding text.tell() at different lines.

    Here is another approach:

    with open("file","r") as file: 
        text=file.readlines() 
    i=0 
    while i < len(text): 
        if keyword in text[i]: 
            text[i]=text[i].replace(keywork,replacement) 
    with open("file","w") as file: 
        file.writelines(text)
    

提交回复
热议问题