如何在Python中拆分文本文件并对其进行修改?
我目前有一个文本文件,如下所示:如何在Python中拆分文本文件并对其进行修改?,python,python-3.x,split,text-files,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 Fr
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;
change_word("Not_Madagascar", 2, 1)
add_line(['this','line','is','at','the','end'], 4) #4 is the line number
我当前正在使用以下代码打印文件:
with open ("base.txt",'r') as f:
for line in f:
words = line.split(';')
for word in words:
print (word)
我想知道的是,如何使用他们的id号修改一行(例如101)并保留其格式,并根据其id号添加或删除行?如果您试图保留原始文件顺序,并且能够引用文件中的行进行修改/添加/删除,则将此文件读入一个
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"
我的理解是,您询问如何修改一行中的单词,然后将修改后的行插入到文件中 更改文件中的单词 要使用此功能设置
第3行,请将单词2
设置为非Madasgascar
如下所示:
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;
change_word("Not_Madagascar", 2, 1)
add_line(['this','line','is','at','the','end'], 4) #4 is the line number
您必须始终将1
添加到行号/字号中,因为第一行/字号是0
向文件中添加新行
要使用此功能,请在末尾添加一行,其中包含单词this
line
is
at
the
end
如下所示:
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;
change_word("Not_Madagascar", 2, 1)
add_line(['this','line','is','at','the','end'], 4) #4 is the line number
有关打开文件的详细信息,请参见
有关读取和修改文件的更多信息,请参阅。是解决您的需求的强大工具。它提供了便于使用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)
不清楚你所说的线是什么意思。您是指文件的一行还是使用split()后的列表元素?split()后的列表元素,然后更改或向这些列表添加文本您是指
line.split(',')
?从您提供的文件中,按拆分行
没什么用。很抱歉,我对这一切都不熟悉,我该如何使用函数[change_word]@Nandito104?别担心!每个人在某个时候都是初学者。我将更改我的帖子,并提供有关使用它的更多详细信息。@Nandito104它已更改。如果我想添加另一行,根据您提供的函数,我将如何进行?您不需要在阅读后查找文件开始吗?坦率地说,使用这种方法,最好先在读取模式下打开文件,然后在写入模式下重新打开。此外,就地更改是有风险的,除非您使用相同大小的片段更改某个特定片段,否则这是不合理的。在这种情况下,建议使用二进制模式。csv编辑器听起来很合适,但您可能需要对命令的作用进行更多的解释。