简体   繁体   中英

Copy from a text file and write to another file the lines numbered

My question is simple.

My task is to read a text file named cities.txt with countries and capitals (eg the first three lines are:

Aberdeen, Scotland

Adelaide, Australia

Algiers, Algeria

)

and write to another text file named out.txt these contents numbered (eg

1: Aberdeen, Scotland

2: Adelaide, Australia

3: Algiers, Algeria

)

My code so far is:

 try: with open('cities.txt', 'r') as f: with open('out.txt', 'w') as m: lines = f.read() #missing code except: print('Error') else: with open('out.txt', 'r') as m: content = m.read() print(content) 

Any ideas?

You could do it, like so:

with open('cities.txt') as infile, open('out.txt', 'w') as outfile:
    in_lines = infile.readlines()
    for i, line in enumerate(in_lines, start=1):
        outfile.write('{}: {}'.format(i, line))

The text written to the out.txt :

1: Aberdeen, Scotland
2: Adelaide, Australia
3: Algiers, Algeria

You just need to loop over each line in the input file and write to the output - and use a counter to keep track of the line number:

with open('cities.txt', 'r') as f:
    with open('out.txt', 'w') as m:
        l = 1
        for line in f:
            m.write("{}: {}".format(l, line))
            l += 1

You can keep it short by opening the files on one line

with open(r'bla.txt', 'r') as fd, open(r'bla2.txt', 'w') as fd2:
    count = 1
    for line in fd.readlines():
        fd2.write(str(count) + ': ' + line)
        count += 1

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