首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python将新列添加到文件的开头

Python将新列添加到文件的开头
EN

Stack Overflow用户
提问于 2017-04-13 14:07:16
回答 3查看 179关注 0票数 2

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

代码语言:javascript
复制
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

我要完成的是在开头添加一列i,所以看起来是这样的,但我不确定我将如何完成它。如果有人能帮我解决这个问题我会很高兴的。

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-04-13 14:18:13

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

Python3

代码语言:javascript
复制
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

代码语言:javascript
复制
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()
票数 1
EN

Stack Overflow用户

发布于 2017-04-13 14:13:31

你用什么字典,一个列表或什么,或只是连接在范围(数据集)的I:‘’.联接([我,数据集])

票数 0
EN

Stack Overflow用户

发布于 2017-04-13 14:17:48

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

代码语言:javascript
复制
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()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43394473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档