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

2024-10-01 11:31:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我当前有一个文本文件,如下所示:

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;

我当前正在使用以下代码打印文件:

^{pr2}$

我想知道的是,我如何修改一行使用他们的id号(例如101),并保持他们的格式,并根据他们的id号添加或删除行?在


Tags: andidenglish文本文件dollarafricamadagascaruganda
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"

^{}是解决您的需求的强大工具。它提供了轻松处理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

^{pr2}$

enter image description here

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

{a4}

我理解你问如何修改一行中的一个词,然后将修改后的行重新插入文件。在

在文件中更改一个单词

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,请按如下方式调用:

^{pr2}$

因为第一行/字是0,所以您必须将1添加到行号/字号中

向文件添加新行

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。在

相关问题 更多 >