我目前有一个文本文件,内容如下:
101, Liberia, Monrovia, 111000, 3200000, Africa, English, Liberia Dollar;
102, Uganda, Kampala, 236000, 34000000, Africa, English and Swahili, Ugandan Shilling;
103, Madagascar, Antananarivo, 587000, 21000000, Africa, Magalasy and Frances, Malagasy Ariary;
我当前正在使用以下代码打印文件:
with open ("base.txt",'r') as f:
for line in f:
words = line.split(';')
for word in words:
print (word)
我想知道的是,如何使用它们的 id 号(例如 101)修改行并保留它们的格式并根据它们的 id 号添加或删除行?
最佳答案
pandas
是解决您需求的强大工具。它提供了轻松处理 CSV 文件的工具。您可以在DataFrames
中管理数据。
import pandas as pd
# read the CSV file into DataFrame
df = pd.read_csv('file.csv', sep=',', header=None, index_col = 0)
print (df)
# eliminating the `;` character
df[7] = df[7].map(lambda x: str(x).rstrip(';'))
print (df)
# eliminating the #101 row of data
df.drop(101, axis=0, inplace=True)
print (df)
关于python - 如何在Python中分割文本文件并修改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987210/