Python 如何向现有txt文件添加新行

Python 如何向现有txt文件添加新行,python,scikit-learn,numbers,export-to-csv,Python,Scikit Learn,Numbers,Export To Csv,我想使用jupyter笔记本在文本文件中插入新行 25.650 166.965 431.000 12.000 67.000 50.190 231.984 801.000 20.000 98.000 77.840 103.143 244.000 9.000 49.000 82.967 82.682 544.000 15.000 71.000``` Data looks like this, i want to insert column names to the top of

我想使用jupyter笔记本在文本文件中插入新行

25.650  166.965 431.000 12.000  67.000
50.190  231.984 801.000 20.000  98.000
77.840  103.143 244.000 9.000   49.000
82.967  82.682  544.000 15.000  71.000```

Data looks like this, i want to insert column names to the top of the these data and save it in a new csv file

您可以使用Pandas将csv文件读取为数据框,添加列名称,然后将其另存为csv文件

import pandas as pd

filename = "your_file.csv"
df = pd.read_csv(filename, header=None)
df.columns = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5']
df.to_csv(filename)
使用
csv
模块有点复杂。创建一个新文件,写入列名,然后写入从原始文件读取的每一行

import csv

new_filename = 'your_new_file.csv'
column_names = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5']
with open(filename, 'r') as infile, open(new_filename, 'w') as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile)
    writer.writerow(column_names)
    for row in reader:
        writer.writerow(row)

您可以利用Jupyter生态系统中的优势,在笔记本中使用shell命令简单地预挂起数据文件。(我假设数据列是以制表符分隔的。)在笔记本中的单元格中,执行以下操作,用文件名替换
data.tsv
,并为占位符添加真实的列名:

!echo -e "col_1\tcol_2\tcol_3\tcol_4\tcol_5\n$(cat data.tsv)" > data.tsv

如果您实际上使用的是逗号分隔的文件,请在我放置
\t
的位置使用逗号,这将添加选项卡。同样,如果数据只是空格分隔的。

请阅读。@JohnGordon您建议将列名放在文件的底部而不是顶部。