Python csv:写入不同目录

-1 投票
3 回答
3186 浏览
提问于 2025-04-18 12:34

我正在从一个网站下载文件,我需要先保存原始文件,然后打开它,再把文件下载的链接和下载日期添加到文件里,最后把这个文件保存到另一个文件夹。

我参考了这个答案来修改csv文件:如何用Python在CSV文件开头添加新列

但是我在调用write()函数之前,想把文件重定向到另一个文件夹时遇到了困难。

最好的办法是先写入文件再移动,还是说在open()函数里就能直接写入到另一个文件夹呢?

if fileName in fileList:
    print "already got file "+ fileName
else:
    # download the file
    urllib.urlretrieve(csvUrl, os.path.basename(fileName))
    #print "Saving to 1_Downloaded "+ fileName

    # open the file and then add the extra columns
    with open(fileName, 'rb') as inf, open("out_"+fileName, 'wb') as outf:
        csvreader = csv.DictReader(inf)

        # add column names to beginning
        fieldnames = ['url_source','downloaded_at'] + csvreader.fieldnames  
        csvwriter = csv.DictWriter(outf, fieldnames)
        csvwriter.writeheader()
        for node, row in enumerate(csvreader, 1):
            csvwriter.writerow(dict(row, url_source=csvUrl, downloaded_at=today))

3 个回答

0

最后我选择了使用shutil这个库来增加一个额外的功能:

# move and rename the 'out_' files to the right dir
source = os.listdir(downloaded)

for files in source:
    if files.startswith('out_'):
        newName = files.replace('out_','')
        newPath = renamed+'/'+newName
        shutil.move(files,newPath)
0

其实不需要重新生成文件,可以试试用时间模块来给你的文件名加个时间戳,然后用os.rename来移动文件。

举个例子 - 这个代码只是把文件移动到你指定的位置:

os.rename('filename.csv','NEW_dir/filename.csv')

希望这对你有帮助。

0

我觉得这两种方法都可以用。

在我看来,最简单的方法是先把内容添加到文件里,然后再把文件移动到其他地方。

你可以看看这个链接:shutil.move

我认为重新写整个文件会比较耗费资源。

撰写回答