Python在fi开头添加新列

2024-06-06 12:54:13 发布

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

我一直在尝试在python中向这个数据集添加一个新的id列

0000008::Edison Kinetoscopic Record of a Sneeze (1894)::Documentary|Short 
0000010::La sortie des usines Lumière (1895)::Documentary|Short
0000012::The Arrival of a Train (1896)::Documentary|Short
25::The Oxford and Cambridge University Boat Race (1895)::
0000091::Le manoir du diable (1896)::Short|Horror
0000417::Le voyage dans la lune (1902)::Short|Adventure|Fantasy
0000439::The Great Train Robbery (1903)::Short|Action|Crime
0443::Hiawatha, the Messiah of the Ojibway (1903)::
0000628::The Adventures of Dollie (1908)::Action|Short

我要做的是在一开始添加一个带有ids的列,这样看起来像这样,但是我不确定该怎么做。如果有人能帮我解决,我会很高兴的。你知道吗

0::0000008::Edison Kinetoscopic Record of a Sneeze (1894)::Documentary|Short 
1::0000010::La sortie des usines Lumière (1895)::Documentary|Short
2::0000012::The Arrival of a Train (1896)::Documentary|Short
3::25::The Oxford and Cambridge University Boat Race (1895)::
4::0000091::Le manoir du diable (1896)::Short|Horror
5::0000417::Le voyage dans la lune (1902)::Short|Adventure|Fantasy
6::0000439::The Great Train Robbery (1903)::Short|Action|Crime
7::0443::Hiawatha, the Messiah of the Ojibway (1903)::
8::0000628::The Adventures of Dollie (1908)::Action|Short

Tags: oftheletrainactionrecordlashort
3条回答

假设输入文件名为in_file,输出文件名为out_file,则可以在Python2或/和Python3中执行类似操作:

Python3

data = (k.rstrip() for k in open("in_file", 'r'))
with open("out_file", 'a+') as f:
    for k,v in enumerate(data):            
        f.write("{0}::{1}\n".format(k,v))

Python2

data = (k.rstrip() for k in open("in_file", 'r'))
f = open("out_file", 'a+')
for k,v in enumerate(data):
    f.write("%d::%s\n" % (k,v))
f.close()

我将把它作为一个简单的for循环来处理现有文件中的行。在循环的每次迭代中,我都会写行号和分隔符,然后打印从旧文件读入的行。你知道吗

infile = open('original_filename', 'r')
outfile = open('new_filename', 'w')
line_counter = 0
for line in infile:
    outfile.write(str(line_counter) + "::" + line)
    line_counter += 1
infile.close()
outfile.close()

你用什么字典列表什么的,还是用join连接 对于范围内的i(数据集): ''.join([i,dataset[i]])

相关问题 更多 >