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

标签 python csv dataset

我一直试图在 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

我要完成的是在开头添加一个带有 id 的列,所以它看起来像这样,但我不确定我会怎么做。如果有人可以帮助我解决它,我会很高兴。

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

最佳答案

假设您的输入文件名为 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()

关于Python 将新列添加到文件的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43394473/

相关文章:

python - 有没有办法让这段代码在计算机上的负担更少?

python - 自动检测文件夹中的文件

python - 子进程不会接受 dxl 脚本的输出

java - JFreeChart 使用颜色映射在 2D 图形中表示 3D 数据

python - 无法从 models.py 导入类

c# - SQL Server - 无法将值 0 或 1 导入位列

mysql - 由 csv 文件加载数据填充的 mysql 表没有结果

excel - 如何防止超过电子表格单元格字符限制的 CSV 数据溢出到相邻单元格?

dataset - 先知预测的诊断问题

visual-studio - Visual Studio 项目 : Properties/Settings. 设置缺失