How do I edit a text file in Python?

前端 未结 4 1478
小鲜肉
小鲜肉 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:38

    Use the fileinput module. (See also the MOTW site.)

    import fileinput
    keyword1 = " i "
    keyword2 = "-i-"
    replacement1 = " I "
    replacement2 = "-I-"
    for line in fileinput.input('your.file', inplace=True):
        line = line.rstrip()
        if keyword1 in line:
            line = line.replace(keyword1, replacement1)
        elif keyword2 in line:
            line = line.replace(keyword2, replacement2)
        print line
    

    The fileinput module, when you use the inplace option, renames the input file and redirects stdout to a new file with the original file name

    If you want to preserve the whitespace on the right of each line, don't rstrip and use print line, (note the final comma) to output the processed lines.

提交回复
热议问题