如何检查文件是否在特定文件夹中?
How to check if a file is in a specific folder?
我有以下结构:
root
|_ Audi
|_file1.txt
|_file2.txt
|_ Mercedes
|_file1.txt
|_file2.txt
我想创建一个函数来检查文件是否在 Audi
或 Mercedes
中。
- 如果文件在`Audi'进程中.....
- 如果文件在
Mercedes
进程中..
这是我的代码:
root = r'C:\data\desktop\my_folder\my_cars'
def move_to_db (path):
ls_mts_raw = []
for file in os.listdir(path):
if file.endswith('.csv'):
file_path = os.path.join(path, file)
move_to_db(root)
这就是我到目前为止所拥有的,但我卡住了......
使用以下代码,您将获得一个以品牌为键、文件名列表为值的字典。
import glob
from pathlib import Path
files = glob.glob(r"./root/*/*.txt") # You can use os.path.join() here
files_by_brand = {}
for file in files:
path = Path(file)
brand_name = path.parent.name
file_name = path.resolve().as_posix()
file_list = files_by_brand.setdefault(brand_name, [])
file_list.append(file_name)
print(files_by_brand)
@Metallimax.
所以我现在这样做了:
import glob
from pathlib import Path
path_root = r'c:\data\FF\Desktop\my_folders\my_cars'
files = glob.glob(path_root) # You can use os.path.join() here
files_by_brand = {}
for file in files:
path = Path(file)
brand_name = path.parent.name
file_name = path.resolve().as_posix()
file_list = files_by_brand.setdefault(brand_name, [])
file_list.append(file_name)
print(files_by_brand)
我收到了这个:
In [37]:runfile('c:/data/FF/Desktop/Python/the_cars.py', wdir='c:/data/FF/Desktop/Python')
{'my_folders': ['C:/data/FF/Desktop/my_folders/my_cars']}
我有以下结构:
root
|_ Audi
|_file1.txt
|_file2.txt
|_ Mercedes
|_file1.txt
|_file2.txt
我想创建一个函数来检查文件是否在 Audi
或 Mercedes
中。
- 如果文件在`Audi'进程中.....
- 如果文件在
Mercedes
进程中..
这是我的代码:
root = r'C:\data\desktop\my_folder\my_cars'
def move_to_db (path):
ls_mts_raw = []
for file in os.listdir(path):
if file.endswith('.csv'):
file_path = os.path.join(path, file)
move_to_db(root)
这就是我到目前为止所拥有的,但我卡住了......
使用以下代码,您将获得一个以品牌为键、文件名列表为值的字典。
import glob
from pathlib import Path
files = glob.glob(r"./root/*/*.txt") # You can use os.path.join() here
files_by_brand = {}
for file in files:
path = Path(file)
brand_name = path.parent.name
file_name = path.resolve().as_posix()
file_list = files_by_brand.setdefault(brand_name, [])
file_list.append(file_name)
print(files_by_brand)
@Metallimax.
所以我现在这样做了:
import glob
from pathlib import Path
path_root = r'c:\data\FF\Desktop\my_folders\my_cars'
files = glob.glob(path_root) # You can use os.path.join() here
files_by_brand = {}
for file in files:
path = Path(file)
brand_name = path.parent.name
file_name = path.resolve().as_posix()
file_list = files_by_brand.setdefault(brand_name, [])
file_list.append(file_name)
print(files_by_brand)
我收到了这个:
In [37]:runfile('c:/data/FF/Desktop/Python/the_cars.py', wdir='c:/data/FF/Desktop/Python')
{'my_folders': ['C:/data/FF/Desktop/my_folders/my_cars']}