使用路径时的文件命名

时间:2015-11-11 17:52:07

标签: python

所以我有以下代码,我正在尝试导出csv并立即在Python中打开它。

# define weekly pull code
def GT_Weekly_Run(keys):
    # connect to Google
    connector = pyGTrends(google_username, google_password)
    # make request
    connector.request_report(keys, geo="US")
    # wait a random amount of time between requests to avoid bot detection
    time.sleep(randint(5, 10))
    # download file
    connector.save_csv(path, '_' + "GT_Weekly" + '_' + keys)

    name = path, '_' + "GT_Weekly" + '_' + keys
    with open(name + '.csv', 'rt') as csvfile:    
        csvReader = csv.reader(csvfile)
        data = []

        data = [row for row in csvReader if row and row[0].startswith("20")]
        week_df = pd.DataFrame(data)

        cols = ["Date", "Trend"]    
        week_df.columns = [cols]   

问题是我无法将保存为文件名与打开的文件名相匹配。尝试了很多事情,但一直有关于

的错误
IOError: [Errno 2] No such file or directory: 'GT_Weekly_football.csv'

TypeError: can only concatenate tuple (not "str") to tuple

有什么可以看的。我只需要将文件保存为X并使用相同的名称(X)将其导入。

谢谢!

1 个答案:

答案 0 :(得分:0)

我建议你创建一个变量来保存文件名。这样,相同的名称将用于创建和加载。

import os 

# define weekly pull code
def GT_Weekly_Run(keys):
    # connect to Google
    connector = pyGTrends(google_username, google_password)
    # make request
    connector.request_report(keys, geo="US")
    # wait a random amount of time between requests to avoid bot detection
    time.sleep(randint(5, 10))

    # download file

    filename = "_GT_Weekly_" + keys
    connector.save_csv(path, filename)

    with open(os.path.join(path, filename), 'rt') as csvfile:    
        csvReader = csv.reader(csvfile)
        data = []

        data = [row for row in csvReader if row and row[0].startswith("20")]
        week_df = pd.DataFrame(data)

        cols = ["Date", "Trend"]    
        week_df.columns = [cols] 

使用Python的os.path.join函数创建完整的文件名更安全。

另请查看您传递给keys的{​​{1}}参数,它应该只是一个简单的字符串。

相关问题