【问题标题】:how to split a text file and modify it in Python?如何拆分文本文件并在 Python 中进行修改?
【发布时间】:2016-12-06 03:12:32
【问题描述】:

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

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 号添加或删除行?

【问题讨论】:

  • 不清楚你所说的一行是什么意思。你是指文件的一行,还是你使用 split() 后的一个列表元素?
  • split() 之后的列表元素,然后将文本更改或添加到这些列表中
  • 您的意思是line.split(',')?从您提供的文件中,将行拆分为; 不会有太大作用。

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


【解决方案1】:

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)

【讨论】:

  • 一个 csv 编辑器听起来很合适,但您可能想对您的命令的作用提供更多解释。
【解决方案2】:

我理解您询问如何修改一行中的一个单词,然后将修改后的行插入回文件中。

更改文件中的一个单词

def change_value(new_value, line_number, column):
    with open("base.txt",'r+') as f: #r+ means we can read and write to the file
        lines = f.read().split('\n') #lines is now a list of all the lines in the file
        words = lines[line_number].split(',')
        words[column] = new_value
        lines[line_number] = ','.join(words).rstrip('\n') #inserts the line into lines where each word is seperated by a ','
        f.seek(0)
        f.write('\n'.join(lines)) #writes our new lines back into the file

为了使用这个函数将line 3, word 2设置为Not_Madasgascar,这样调用它:

change_word("Not_Madagascar", 2, 1)

您将始终必须将1 添加到行/单词编号,因为第一行/单词是0

在文件中添加新行

def add_line(words, line_number):
    with open("base.txt",'r+') as f:
        lines = f.readlines()
        lines.insert(line_number, ','.join(words) + '\n')
        f.seek(0)
        f.writelines(lines)

为了使用这个函数,在末尾添加一行包含thislineisattheend这样的单词:

add_line(['this','line','is','at','the','end'], 4) #4 is the line number

有关打开文件的更多信息,请参阅here

有关读取和修改文件的更多信息,请参阅here

【讨论】:

  • 对不起,我对这一切还很陌生,我将如何使用该功能 [change_word]
  • @Nandito104 不用担心!每个人在某些时候都是初学者。我将更改我的帖子将更多使用它的详细信息。
  • @Nandito104 变了。
  • 如果我想添加另一行,根据你给我的功能,我该怎么做?
  • 读取后不需要seek文件启动吗?坦率地说,使用这种方法,最好先以读取模式打开文件,然后以写入模式重新打开它。此外,就地更改是有风险的业务 - 除非您使用相同大小的片段更改确定的片段,否则这是不合理的。在这种情况下,建议使用二进制模式
【解决方案3】:

如果您尝试保留原始文件的顺序并能够引用文件中的行以进行修改/添加/删除,则将此文件读入OrderedDict 可能会有所帮助。在以下示例中,对文件的完整格式有很多假设,但它适用于您的测试用例:

from collections import OrderedDict

content = OrderedDict()

with open('base.txt', 'r') as f:
    for line in f:
        if line.strip():
            print line
            words = line.split(',')  # Assuming that you meant ',' vs ';' to split the line into words
            content[int(words[0])] = ','.join(words[1:])

print(content[101])  # Prints " Liberia, Monrovia, etc"...

content.pop(101, None)  # Remove line w/ 101 as the "id"

【讨论】:

    猜你喜欢
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-07
    相关资源
    最近更新 更多