Python csv:写入不同的目录
我正在从网站下载文件,我需要保存原始文件,然后打开它,然后在将文件保存到其他目录之前,将下载文件的url和下载日期添加到文件中 我用这个答案修改了csv: 但是在调用write()函数之前,我很难将文件重定向到其他目录 是写入文件然后移动它的最佳解决方案,还是有办法将文件写入open()函数中的其他目录Python csv:写入不同的目录,python,csv,Python,Csv,我正在从网站下载文件,我需要保存原始文件,然后打开它,然后在将文件保存到其他目录之前,将下载文件的url和下载日期添加到文件中 我用这个答案修改了csv: 但是在调用write()函数之前,我很难将文件重定向到其他目录 是写入文件然后移动它的最佳解决方案,还是有办法将文件写入open()函数中的其他目录 if fileName in fileList: print "already got file "+ fileName else: # download the file
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))
我相信两者都能奏效。
在我看来,最整洁的方法是附加到文件中,然后重新定位它
看看:
我认为重写整个文件的效率较低。无需重建文件,请尝试使用时间模块为文件名创建时间戳字符串,并使用os.rename移动文件 示例-这只是将文件移动到指定位置: 重命名('filename.csv','NEW_dir/filename.csv')
希望这能有所帮助。最后使用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)
您正在创建一个新的输出文件吗?是的,我需要创建一个新的输出文件。为什么不在打开时只在您要保存它的目录中创建文件呢?您是否对代码进行了计时以查看哪个更有效?代码每周运行一次,因此速度不是最重要的因素,我只想尽可能少写几行(以后出错的次数更少)。我必须以原始“未接触”状态(inc文件名)保存文件副本,以提供源数据的准确存档,然后将所有修改保存到diff目录。谢谢你的建议。操作系统。重命名。。。那会很好的谢谢你。