简体   繁体   English

从文本文件复制并将行编号写入另一个文件

[英]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: 我的任务是读取一个带有国家和大写字母的名为city.txt的文本文件(例如,前三行是:

Aberdeen, Scotland 苏格兰阿伯丁

Adelaide, Australia 澳大利亚阿德莱德

Algiers, Algeria 阿尔及尔,阿尔及利亚

)

and write to another text file named out.txt these contents numbered (eg 并将这些已编号的内容写入另一个名为out.txt的文本文件中(例如

1: Aberdeen, Scotland 1:苏格兰阿伯丁

2: Adelaide, Australia 2:澳大利亚阿德莱德

3: Algiers, Algeria 3:阿尔及利亚阿尔及尔

)

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 : 写入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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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