简体   繁体   English

Python os.getcwd路径

[英]Python os.getcwd paths

I'm using os.listdir() to get all the files from a directory and dump them out to a txt file. 我正在使用os.listdir()从目录中获取所有文件,并将其转储到txt文件中。 I'm going to use the txt file to import into access to generate hyperlinks. 我将使用txt文件导入访问权限以生成超链接。 The problem I'm having is getting the correct path. 我遇到的问题是获得正确的路径。 So when the script is ran it uses whatever directory you are in. Here is an example. 因此,运行脚本时,它将使用您所在的目录。这是一个示例。 Right now it half works, it create links.txt, but there is nothing in the text file. 现在它可以正常工作了,它创建了links.txt,但是文本文件中没有任何内容。

myDirectory = os.listdir("links")
f.open("links.txt", "w")
f.writelines([os.getcwd %s % (f) for f in myDirectory])

This line of yours: 您的这一行:

f.writelines([os.getcwd %s % (f) for f in myDirectory])

is invalid Python syntax and it's very hard to guess what you had in mind for it -- for example, why would you care about the current directory when myDirectory lists, not files in the current directory, but rather files in subdirectory "links"? 是无效的Python语法,很难猜测出它的初衷-例如,当myDirectory列出而不是当前目录中的文件,而是子目录“链接”中的文件时,为什么还要关心当前目录?

Trying to read your mind is always a difficult and generally unrewarding exercise, but assuming you do mean to use the current directory, you might want 尝试读心术始终是一项困难且通常毫无用处的练习,但是假设您确实要使用当前目录,则可能需要

 f.writelines(os.path.join(os.getcwd(), f) for f in myDirectory)

You have to call os.getcwd() with the trailing parens. 您必须使用尾随的括号调用os.getcwd()

What you probably actually want here though is os.path.join() 您实际上可能真正想要的是os.path.join()

os.getcwd is a function you need to call... also I'm not sure what you're doing with the string escape % - but they only work inside strings... I'm guessing you want something like this: os.getcwd是您需要调用的函数...我也不知道您在使用字符串转义%做什么-但它们仅在字符串中起作用...我猜您想要这样的东西:

f.writelines([os.path.join(os.getcwd(),f) for f in myDirectory])

[Edit: os.path.join from Alex Martelli's better answer] [编辑:os.path.join,来自Alex Martelli的更好答案]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM