Python 更改目录时路径中的语法无效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19080128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:46:43  来源:igfitidea点击:

Invalid syntax in path when changing directory

pythondirectorydircd

提问by turnip

In Python, first I check where I am:

在 Python 中,首先我检查我在哪里:

import os
os.getcwd()

This gives me %run C:/Users/<name>/Desktop/<script.py>Now I want to change where I am:

这给了我%run C:/Users/<name>/Desktop/<script.py>现在我想改变我的位置:

os.chdir("C:/Users/<name>/Desktop/")

This gives me

这给了我

%run C:/Users/<name>/Desktop/<script.py>
  File "C:\Users\<name>\Desktop\<script.py>", line 3
    os.chdir("/C:/Users/<name>/Desktop/")
              ^
SyntaxError: invalid syntax

I have tried variations of this but nothing seems to work.

我尝试过这种变体,但似乎没有任何效果。

采纳答案by ChrisProsser

There are a number of ways that you can do this including:

有多种方法可以做到这一点,包括:

Using os.path to join a path and an environment variable:

使用 os.path 连接路径和环境变量:

os.chdir(os.path.join(os.getenv('userprofile'),'Desktop'))

You could alternatively use either double backslashes (backslash needs to be escaped in Python strings):

您也可以使用双反斜杠(反斜杠需要在 Python 字符串中转义):

os.chdir('c:\users\prosserc\desktop')

or use a raw string:

或使用原始字符串:

os.chdir(r'c:\users\prosserc\desktop')

I would recommend the first option as it does require a hard coded user name.

我会推荐第一个选项,因为它确实需要一个硬编码的用户名。

回答by Marin

You can do code like this:

你可以做这样的代码:

path = "full path to your directory"
dirs = os.listdir(path)
#some code