首页 > 解决方案 > How to edit a text file?

问题描述

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.

Does anyone know how to do this?

标签: pythonfiletextpython-3.7

解决方案


如果这是一个类似 csv 的文件,您可能需要使用 pandas(这是数据框操作的最佳方法之一)。一个简单的例子:

import pandas as pd
df = pd.read_csv("<path_to_data_file>", header=None)
df = pd.concat([df, df])
df[0] = list(range(1, 11))
df.to_csv("result.csv", header=None, index=None)

推荐阅读