从/向不同的本地文件夹读/写csv

时间:2018-01-16 11:48:50

标签: python csv writer os.path tab-delimited

我想在本地文件夹中打开一个文件,添加注释,然后将其保存在另一个名称不同的本地文件夹中。 下面的代码将注释添加到文件中,但随后覆盖输入df上的输出。

import csv
import os.path
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]}) # assume my csv (my_df.csv) looks like this dataframe
folder_input = '/my_folder/input/'
CSV_IN = os.path.join(folder_input, "my_df.csv")

folder_out = '/my_folder/output/'

with open('CSV_IN', 'r+') as f:
    content = f.read()
    f.seek(0, 0)
    f.write('my personal comment' + content)
    writer = csv.writer(f,delimiter='\t') # here I would like to specify the folder
                                          # where to save the file (foder_out) 
                                          # and also the file name

另外,我可以使用扩展名.tab 而不是使用制表符分隔符的csv保存输出文件吗? 感谢

3 个答案:

答案 0 :(得分:2)

您需要两个目标文件,一个用于输入,另一个用于输出:

import csv
import os.path
df = pd.DataFrame({"a": [1,2,3,4,5], "b": [6,7,8,9,10], "c": [11,12,13,14,15]}) # assume my csv (my_df.csv) looks like this dataframe
folder_input = '/my_folder/input/'
CSV_IN = os.path.join(folder_input, "my_df.csv")

folder_out = '/my_folder/output/'
CSV_OUT = os.path.join(folder_out, "my_df.tab")

with open(CSV_IN, 'r+') as f_in, open(CSV_OUT, 'w') as f_out:
    content = f_in.read()
    f_out.write('my personal comment' + content)

如果您不想保留原始文件,则需要在使用os.remove()完成副本后明确删除它:

import os
# After the previous code...
os.remove(CSV_IN)

答案 1 :(得分:1)

.csv可以在不同的文件夹中读取并保存为.tab,评论如下:

import csv
import os

folder_input = '/Users/ilayaraja'
folder_out = '/Users/ilayaraja/Desktop/'
file_input = "my_df.csv"
file_out = "my_df.tab"

with open(os.path.join(folder_input, file_input), "r") as inf, \
    open(os.path.join(folder_out, file_out), "w") as outf:
    outf.write("##Comment here##\n")
    reader = csv.reader(inf)
    writer = csv.writer(outf, delimiter="\t")
    for row in reader:
        writer.writerow(row)

答案 2 :(得分:0)

从with语句中取出写行。然后启动另一个with语句,在写入模式('w')中打开一个新文件(新名称不会覆盖以前的文件)。然后在这第二个声明下你写了写行。