简体   繁体   中英

Take first line from file A and insert in file B at a specific line

I am trying to copy line number 1 from file A and paste it into line number 230 in file B without touching the existing text in file B.

In other words replace only line nr. 230 in file B with line nr. 1 from file A.

Here is my code:

inputFile = open("A.txt", "r")
lines = inputFile.readlines()[0] #get 1st line from file A
outputFile = open("B.txt", "w")
for i, line in enumerate(lines):
       if 'Trim\n' in line:      #'Trim' is the text on line 230 in file B
          lines.insert(i, lines)
outputFile.truncate(0)
outputFile.seek(0) 
outputFile.writelines(lines)

With this I end up with the correct line written into file B from file A but on the first line and it removes all original text and data in file B.

How can I only insert the line into file B on line nr. 230 without erasing all its text?

You cannot "insert" a line into a file, as such. A file is a positional data structure, each character having its own position in the file. To get what you want, you will have to save the entire file from the point of insertion, onward; write the new data at the point of insertion; and re-write the remaining file into their new positions.

Your code searches for the Trim line in file B correctly. However, it ignores everything else in B . You save that one line. Then you remove the entire file and write only that one line. You are quite explicit about that.

Instead, save the entire file with a readlines command:

addLine = inputFile.readline()  # Since you want the first line, read only that one.
lines = outputFile.readlines()
for i, line in enumerate(lines):
    if 'Trim\n' in line:
        lines.insert(i, addLine)
        break

Now, write the entire contents of lines into file B.

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