简体   繁体   中英

Add numbers from a list to an existing file using python

I have a text file with say 14 lines, and I would like to add list items from a list to the end of each of these lines, starting with the 5th line. Can anyone help me out please. eg I have this text file called test.txt :

a b
12
1
four
/users/path/apple 
/users/path/banana 
..
..

and I have the following list

cycle=[21,22,23,.....]

My question is how can add these list items to the end of the lines such that I get this:

a b
12
1
four
/users/path/apple 21
/users/path/banana 22
..
..

I am not very good at python and this seems like a simple problem. Any help would be appreciated.

Something like this:

for line in file.readlines():
    print line.rstrip(), cycle.pop(0) 
cycle = [21, 22, 23]
i = 0
with open('myfile.txt', 'r') as fh:
    with open('new_myfile.txt', 'w' as fh_new:
        for line in fh:
            addon = ''
            if i < len(cycle):
                addon = cycle[i]
            fh_new.write(line.strip() + addon + '\n')
            i += 1            

In general, you cannot modify a file except to append things at the end of the file (after the last line).

In your case, you want to:

  1. Read the file, lines by lines
  2. Append something to the line (optionally)
  3. Write that line back.

You can do it in several ways. Load -> Write back modified string would be the simplest:

with open("path/to/my/file/test.txt", 'rb') as f:
    # Strip will remove the newlines, spaces, etc...
    lines = [line.strip() for line in f.readlines()]
numbers = [21, 22, 23]
itr = iter(numbers)
with open("path/to/my/file/test.txt", 'wb') as f:
    for line in lines:
        if '/' in line:
            f.write('%s %s\n' % (line, itr.next()))
        else:
            f.write('%s\n' % line)

The issue with this method is that if you do a mistake with your processing, you ruined the original file. Other methods would be to:

  • Do all the modifications on the list of lines, check, and write back the whole list
  • Write back into a newly created file, possibly renaming it in the end.

As always, the Python doc is a definitely good read to discover new features and patterns.

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