我正在尝试从文件夹目录中打印所有文件的名称。我有一个名为“a”的文件夹,在该文件夹中有3个NC文件,我们称之为“b”,“c”,“d”,我想要打印的目录。我该怎么做?
例如,给定我的文件夹路径是
path=r"C:\\Users\\chz08006\\Documents\\Testing\\a"
我想将目录打印到文件夹“a”中的所有文件,因此结果应该打印:
C:\\Users\\chz08006\\Documents\\Testing\\a\\b.nc
C:\\Users\\chz08006\\Documents\\Testing\\a\\c.nc
C:\\Users\\chz08006\\Documents\\Testing\\a\\d.nc
到目前为止,我已经尝试过了
for a in path:
print(os.path.basename(path))
但这似乎不对。
我想你正在寻找这个:
import os
path = r"C:\\Users\\chz08006\\Documents\\Testing\\a"
for root, dirs, files in os.walk(path):
for file in files:
print("{root}\\{file}".format(root=root, file=file))
您可以使用listdir()
在文件夹中包含文件名列表。
import os
path = "C:\\Users\\chz08006\\Documents\\Testing\\a"
l = os.listdir(path)
for a in l:
print(path + a)
你犯了几个错误。您使用的是os.path.basename
,它仅返回在最后一个文件分隔符之后的路径末尾表示的文件或文件夹的名称。
相反,使用os.path.abspath
来获取任何文件的完整路径。
另一个错误是在循环中使用错误的变量(print(os.path.basename(path)
而不是使用变量a
)
另外,不要忘记在循环之前使用os.listdir
列出文件夹中的文件。
import os
path = r"C:\Users\chz08006\Documents\Testing\a"
for file in os.listdir(path): #using a better name compared to a
print(os.path.abspath(file)) #you wrote path here, instead of a.
#variable names that do not have a meaning
#make these kinds of errors easier to make,
#and harder to spot