Replace a word in a file

后端 未结 4 1624
被撕碎了的回忆
被撕碎了的回忆 2021-01-23 04:36

I am new to Python programming...

I have a .txt file....... It looks like..

0,Salary,14000

0,Bonus,5000

0,gift,6000

I want to to replace

4条回答
  •  無奈伤痛
    2021-01-23 05:24

    inFile = open("old.txt", "r")
    outFile = open("new.txt", "w")
    for line in inFile: 
        outFile.write(",".join(["1"] + (line.split(","))[1:]))
    
    inFile.close()
    outFile.close()
    

    If you would like something more general, take a look to Python csv module. It contains utilities for processing comma-separated values (abbreviated as csv) in files. But it can work with arbitrary delimiter, not only comma. So as you sample is obviously a csv file, you can use it as follows:

    import csv
    reader = csv.reader(open("old.txt"))
    writer = csv.writer(open("new.txt", "w"))
    writer.writerows(["1"] + line[1:] for line in reader)
    

    To overwrite original file with new one:

    import os
    os.remove("old.txt")
    os.rename("new.txt", "old.txt")
    

    I think that writing to new file and then renaming it is more fault-tolerant and less likely corrupt your data than direct overwriting of source file. Imagine, that your program raised an exception while source file was already read to memory and reopened for writing. So you would lose original data and your new data wouldn't be saved because of program crash. In my case, I only lose new data while preserving original.

提交回复
热议问题