tcp*_*008 63
import os
import glob
path = 'c:\\'
extension = 'csv'
os.chdir(path)
result = glob.glob('*.{}'.format(extension))
print(result)
Run Code Online (Sandbox Code Playgroud)
Ber*_*ler 30
from os import listdir
def find_csv_filenames( path_to_dir, suffix=".csv" ):
filenames = listdir(path_to_dir)
return [ filename for filename in filenames if filename.endswith( suffix ) ]
Run Code Online (Sandbox Code Playgroud)
该函数find_csv_filenames()
返回一个文件名列表作为字符串,它们驻留在path_to_dir
具有给定后缀的目录中(默认情况下为".csv").
附录
如何打印文件名:
filenames = find_csv_filenames("my/directory")
for name in filenames:
print name
Run Code Online (Sandbox Code Playgroud)
The*_* PR 14
通过使用过滤器和 lambda 的组合,您可以轻松过滤掉给定文件夹中的 csv 文件。
import os
all_files = os.listdir("/path-to-dir")
csv_files = list(filter(lambda f: f.endswith('.csv'), files))
# lambda returns True if filename name ends with .csv or else False
# and filter function uses the returned boolean value to filter .csv files from list files.
Run Code Online (Sandbox Code Playgroud)
使用Python OS模块在目录中查找csv文件.
这里有一个简单的例子:
import os
# This is the path where you want to search
path = r'd:'
# this is the extension you want to detect
extension = '.csv'
for root, dirs_list, files_list in os.walk(path):
for file_name in files_list:
if os.path.splitext(file_name)[-1] == extension:
file_name_path = os.path.join(root, file_name)
print file_name
print file_name_path # This is the full path of the filter file
Run Code Online (Sandbox Code Playgroud)
我必须获取csv
子目录中的文件,因此,使用来自tchlpr的响应,我对其进行了修改以使其最适合我的用例:
import os
import glob
os.chdir( '/path/to/main/dir' )
result = glob.glob( '*/**.csv' )
print( result )
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
62798 次 |
最近记录: |