Python创建文件时,如果没有指定位置的话,会将该文件放在“C:\Users\...”目录下。如果不知道的话,就会比较懵逼。
下面是在指定位置创建文件,并且遍历目录下所有同名文件的Python程序。
# -*- coding: utf-8 -*-
#查找某个目录下的目标文件
import os #引入操作系统模块
info = 'hello python'
file = open('D:\\Python\\result.txt','a')
file = file.write(info)
def search(path,name):
flag = -1
for root, dirs, files in os.walk(path): # path 为根目录
if name in dirs or name in files:
flag = 1
root = str(root)
dirs = str(dirs)
print(os.path.join(root, dirs))
return flag
print('请输入您要查找哪个盘中的文件(如:D:\\)')
path = input()
print('请输入您要查找的文件名:\n')
name = input()
answer = search(path, name)
if answer == -1:
print("查无此文件")
%run "D:/Python/src/FileHandle/FileOperation.py"
请输入您要查找哪个盘中的文件(如:D:\)
D:
请输入您要查找的文件名:
result.txt
D:Python\['Book', 'Canopy', 'ReadMe', 'src', 'tools', '教学视频']
D:Python\src\['Crawler', 'FileHandle']