整数值错误Python写文件

时间:2013-07-28 18:22:32

标签: python python-2.7

我正在尝试构建一个脚本,该脚本将扫描网站,创建带时间戳的文件夹,然后将带时间戳的文件放入文件夹中。我能够让脚本扫描网站并制作带时间戳的文件,但是当我尝试获取动态命名文件夹时,我收到错误。我发布了工作代码,注释掉了破碎的代码。我不知道该怎么办,欢迎任何建议。

ValueError: mode string must begin with one of 'r', 'w', 'a' or 'U', not
'dataC1-07-28-2013.csv'

这是代码,非工作代码被注释掉:

import urllib2
import datetime
#import os

today = datetime.date.today()
todayDate = today.strftime('%m-%d-%Y')

#newpath = '/home/blah/Data ' + todayDate
#if not os.path.exists(newpath): os.makedirs(newpath)

print "starting load for", todayDate

stub = "http://website.ashx?v=151&c="
for i in range(1, 66):
    print "getting", i, "..."
    data = urllib2.urlopen(stub + str(i)).read()
    f = open("fooC" + str(i) + "-" + todayDate +".csv", "w")
#   f = open('newpath',"fooC" + str(i) + "-" + todayDate +".csv", "w")
    f.write(data)
    f.close()

print "load complete!"

2 个答案:

答案 0 :(得分:3)

您需要构建绝对路径,最好使用os.path.join()

f = open(os.path.join('newpath', "fooC" + str(i) + "-" + todayDate +".csv"), "w")

open()不会采用单独的目录和文件名参数,第二个参数始终是mode参数。

答案 1 :(得分:1)

在你注释掉的打开中你输入三个参数,而它只需要两个(找到文档here):文件名和打开它的模式(读,写等)。

要在新子目录中打开文件,您必须使用os.path.join来获取文件(您可以阅读有关其工作原理的更多信息here)。一个例子:

with open(os.path.join(path,filename), "w") as f:
    #Here do what you want with the file

希望这会有所帮助。同样打开带有块的文件比打开它更安全,就像我说的那样。

相关问题