如何将列添加到现有的csv文件?

时间:2019-07-03 15:36:48

标签: python python-2.7 multiple-columns

我有这段代码可以读取我的csv文件(p01_results,p02_results,.....)以根据其编号从其中删除一些不需要的行,并且它可以正常工作。现在,我尝试添加两列participantIDsession。对于participantID,我尝试读取csv文件的名称,保存ID号(01,02,...)并用它填充列。对于session,我尝试用1、2、3和4填充每18行。

我试图在我的代码中使用此代码,但是没有用:

test4 = ['test4', 4, 7, 10]

with open(data.csv, 'r') as ifile 
    with open(adjusted.csv, 'w') as ofile:
        for line, new in zip(ifile, test4):
            new_line = line.rstrip('\n') + ',' + str(new) + '\n'
            ofile.write(new_line)

import os



base_directory = 'C:\\Users\\yosal\\Desktop\\results'    
for dir_path, dir_name_list, file_name_list in os.walk(base_directory):
    for file_name in file_name_list:
        # If this is not a CSV file
        if not file_name.endswith('results.csv'):
            # Skip it
            continue
        file_path = os.path.join(dir_path, file_name)
        with open(file_path, 'r') as ifile:
            line_list = ifile.readlines()
        with open(file_path, 'w') as ofile:
            # only write these rows to the new file
            ofile.writelines(line_list[0])
            ofile.writelines(line_list[2:20])
            ofile.writelines(line_list[21:39])
            ofile.writelines(line_list[40:58])
            ofile.writelines(line_list[59:77])

3 个答案:

答案 0 :(得分:0)

尝试将CS​​V读取到列表中。然后,遍历列表中的每个元素(每个元素都是CSV中的一行),并添加一个带有反斜线的字符串以及所需的字符串。然后,编写一个新的CSV,以不同的名称命名或替换旧的CSV,然后将您的列表用作输入。

答案 1 :(得分:0)

我尝试使用熊猫在我的csv文件中添加一列。所以您可以尝试这样的事情。首先,您必须通过运行“ pip install pandas”来安装pandas。

import pandas as pd
df = pd.read_csv('data.csv')  ## read  the csv file
df.set_index('S/N', inplace=True) ## you can set an index with any column 
                                  ##you have that already exists in your csv 
                                  ##in my case it is the "S/N" column i used 
df["test"] = ["values","you want","add"]
df.to_csv('data.csv')

答案 2 :(得分:0)

花一些时间,但我做到了。


import os



base_directory = 'C:\\Users\\yosal\\Desktop\\results'    
for dir_path, dir_name_list, file_name_list in os.walk(base_directory):
    for file_name in file_name_list:
        # If this is not a CSV file
        if not file_name.endswith('results.csv'):
            # Skip it
            continue
        file_path = os.path.join(dir_path, file_name)
        with open(file_path, 'r') as ifile:
            line_list = ifile.readlines()
        with open(file_path, 'w') as ofile:
            ofile.writelines(str(line_list[0]).rstrip()+",participant,session\n")
            for x in range(2, 20):
                 ofile.writelines(str(line_list[x]).rstrip()+","+file_path[len(base_directory)+2:len(base_directory)+4]+",1\n")
            for y in range(21, 39):
                 ofile.writelines(str(line_list[y]).rstrip()+","+file_path[len(base_directory)+2:len(base_directory)+4]+",2\n")
            for h in range(40, 58):
                ofile.writelines(str(line_list[h]).rstrip()+","+file_path[len(base_directory)+2:len(base_directory)+4]+",3\n")
            for z in range(59 ,77):
                ofile.writelines(str(line_list[z]).rstrip()+","+file_path[len(base_directory)+2:len(base_directory)+4]+",4\n")