1

我在 Python 中创建了大约 200 个 csv 文件,现在需要全部下载。

我使用以下方法从单个文件创建了文件:

g = df.groupby("col")
for n,g in df.groupby('col'):
    g.to_csv(n+'stars'+'.csv')

当我尝试使用相同的语句导出到我的机器时,我得到一个语法错误,我不确定我做错了什么:

g = df.groupby("col")
for n,g in df.groupby('col'):
    g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'')

错误:

  File "<ipython-input-27-43a5bfe55259>", line 3
    g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'')
                                                 ^
SyntaxError: invalid syntax

我在 Jupyter 实验室,所以我可以单独下载每个文件,但我真的不想这样做。

4

2 回答 2

2

您可能混淆了整数和字符串,并且在文字中使用反斜杠无论如何都是危险的。考虑使用以下

import os

循环内

    f_name = os.path.join('C:', 'users', ' egagne', 'Downloads', str(n), 'stars.csv')
    g.to_csv(f_name)

os.path.join您处理反斜杠。

于 2018-05-17T16:41:26.700 回答
1

g.to_csv('C:\Users\egagne\Downloads\'n+'stars'+'.csv'') needs to be g.to_csv('C:\\Users\\egagne\\Downloads\\'+n+'stars.csv').

There were two things wrong -- the backslash is an escape character so if you put a ' after it, it will be treated as part of your string instead of a closing quote as you intended it. Using \\ instead of a single \ escapes the escape character so that you can include a backslash in your string.

Also, you did not pair your quotes correctly. n is a variable name but from the syntax highlighting in your question it is clear that it is part of the string. Similarly you can see that stars and .csv are not highlighted as part of a string, and the closing '' should be a red flag that something has gone wrong.

Edit: I addressed what is causing the problem but Ami Tavory's answer is the right one -- though you know this is going to run on windows it is a better practice to use os.path.join() with directory names instead of writing out a path in a string. str(n) is also the right way to go if you are at all unsure about the type of n.

于 2018-05-17T16:38:40.480 回答