python - 如何在Python中分割文本文件并修改它?

标签 python python-3.x split text-files

我目前有一个文本文件,内容如下:

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)

enter image description here

# eliminating the `;` character
df[7] = df[7].map(lambda x: str(x).rstrip(';'))
print (df)

enter image description here

# eliminating the #101 row of data
df.drop(101, axis=0, inplace=True)
print (df)

enter image description here

关于python - 如何在Python中分割文本文件并修改它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987210/

相关文章:

Java拆分函数消除空格

c - 将文件中的字符串拆分为c中的数组

python - 按位置循环二维数组

Python pandas,用同一列上的先前值替换列上的 NAN

python - 将 Linux 引导选项传递给 Init

python - 计算数据框中的元素数量

algorithm - Rabin Karp算法的一点修改版本的可行性

r - 拆分字符串并仅保留一个特定部分

python - 根据规则将数字转换为另一个数字

python - 从字典中获取值而不链接到内存位置