如何编辑文本文件? [英] How to edit a text file?

查看:42
本文介绍了如何编辑文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 python 3.7 中编辑文本文件.基本上,我有一个包含数字的文本文件 (file_1.txt) - 像这样的 3 列和 5 行

I am trying to edit a text file in python 3.7. Basically, I have a text file (file_1.txt) that contains numbers - 3 columns and 5 rows like this one

1, 10, 20
2, 20, 30
3, 30, 50
4, 35, 60
5, 50, 100

我想编辑那个文件以获得一些不同的东西,基本上是这个

I would like to edit that file in order to get something a little bit different, basically this

1, 10, 20
2, 20, 30
3, 30, 50
4, 35, 60
5, 50, 100
6, 10, 20
7, 20, 30
8, 30, 50
9, 35, 60
10, 50, 100

复制第二列和第三列,第一列以数字继续,每新行添加一个.我试图这样做,但我没有成功.这是我尝试过的:

The second and third column are copied, and the first column is continuing with numbers, adding one each new line. I was trying to do this but I wasn't successful. Here is what I've tried:

with open("file_1.txt", "r+") as file1:
    file1.read()
    i = 6
    imax = 10
    while i <= imax:
        sentence = str(i) + "\n"
        file1.write(sentence)
        i = i + 1

我不明白如何复制第二列和第三列.

I don't understand how to copy the second and third column.

有人知道怎么做吗?

推荐答案

下面的脚本将构建新文件,您可以设置要创建的行数.

Script below will build new file and you can set number of lines that you want to create.

首先从输入文件中读取所有行,然后将您设置的行数写入新文件.

First all lines are read from input file and then it writes number of lines you set to new file.

list_emitter 可以无限地从给定列表中生成项目,因此您只需调整 output_lines_count 变量即可使您的输出文件更大.

list_emitter can infinitely yield items from given list, so you can just adjust output_lines_count variable to make your output file even bigger.

def list_emitter(l):
    """This generator will endlessly yield items from given list."""
    while True:
        for item in l:
            yield item


with open('file_1.txt') as input_file:
    lines = input_file.readlines()    # Create list of lines

with open('output_file.txt', 'w') as output_file:
    output_lines_count = 10 # Set how many output lines you want
    for counter, line in enumerate(list_emitter(lines)):
        if counter == output_lines_count:
            break
        first, second, third = line.strip().split() # Parse line
        output_file.write('{}, {} {}\n'.format(counter+1, second, third))

这篇关于如何编辑文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆