简体   繁体   English

For循环读取文件名

[英]For loop to read file names

I am new to python. 我是python的新手。 I want to create a for loop that prints all the file names in my folder. 我想创建一个for循环,该循环打印我的文件夹中的所有文件名。

This is what I have : 这就是我所拥有的:

import cf 
f = cf.read('/home/cd_files')
for i in f: 
  print f 

The file names are string values. 文件名是字符串值。 I am guessing what I failed to include in my code. 我猜我未能包含在代码中。

import os
for file in os.listdir('your/directory'):
    print(file)

you can try below code to print all the files under the directory and sub directories. 您可以尝试以下代码来打印目录和子目录下的所有文件。

   for root, dir, files in os.walk("/home/cd_files"):
        for file in files:
            print file
import os
files = os.listdir('your_directory/')
for file in files:
    print(file)

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

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