简体   繁体   中英

How to edit each line of a text file and write to a new file

My first text file has lines of text for example John Smith:Year 13:12/12/2000 I want to edit each line for example John Smith:Year 13:12/12/2000:Non Active

myFile = open("Books.txt", "r")
for line in myFile:

        print(line)
        AddPubDate = ":",input("Enter the publication date for book above")
        myFile2 = open("Books2.txt", "a")
        NewLine = str(line) + str(AddPubDate)

        myFile2.write(NewLine)
        print(NewLine)
myFile.close()
myFile2.close()
print("Process complete")A

This should work:

myFile = open("Books.txt", "r")
myFile = myFile.read()
lines = myFile.split("\n")
for txt in lines:

        print(txt)
        AddPubDate = ":",input("Enter the publication date for book above")
        NewLine = str(txt) + str(AddPubDate)
        with open("books2.txt", "a") as f:
            f.write(NewLine+"\n")
            print(NewLine)
myFile.close()
print("Process complete")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM