python - 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?
解决方案
如果这是一个类似 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)
推荐阅读
- bash - bash 读取和写入具有不寻常布局的配置文件
- javascript - Javascript查找唯一字母
- c# - C# python http 发布到 C# httpwebrequest
- swift - 为什么单边范围不涵盖 Swift switch 语句中的所有情况?
- python - 使用 PyGame 显示 Sci Py voronoi 边缘会产生奇怪的“星形”效果
- gerrit - Gerrit 无法同时显示已验证和代码审查标签
- java - File类是如何实现多平台的
- php - 将数据输入到 php 表单中,而不是填充 MySQL 表
- nginx - vagrant如何使用公共IP访问Web服务器(nginx)
- node.js - 如何从 Slack 获取用户 ID 到机器人服务