1、python获取当前文件下的所有文件名(txt)
import os
def getAllFiles(targetDir):
listFiles = os.listdir(targetDir)
return listFiles
files = getAllFiles(r"D:\test")
with open(r"test.txt",'w+',encoding='utf-8')as f:
f.writelines(["'"+str(i)+"',\n" for i in files])
运行效果图
1.1、其他版本
import os
path = "D:\test"
file_name_list = os.listdir(path)
file_name = str(file_name_list)
file_name = file_name.replace("[", "").replace("]", "").replace("'", "").replace(",", "\n").replace(" ", "")
f = open(path + "\\" + "文件list.txt", "a")
f.write(file_name)
2、pthon文件的读取与写入(yaml)
from shutil import copyfile
from sys import exit
import re
import time
import os
import yaml
def getAllFiles(targetDir):
files = []
listFiles = os.listdir(targetDir)
for i in range(0, len(listFiles)):
path = os.path.join(targetDir, listFiles[i])
if os.path.isdir(path):
files.extend(getAllFiles(path))
elif os.path.isfile(path):
files.append(path)
return files
files = getAllFiles(r"C:\Users\rc\Pictures\壁纸精选500张(四)")
a=files
with open('ee.yaml','w+',encoding='utf-8')as f:
yaml.dump(data=a, stream=f, allow_unicode=True)
with open("ee.yaml",'r',encoding="utf-8") as f:
data=yaml.load(stream=f, Loader=yaml.FullLoader)
print(data, type(data))
for i in range(0,len(data)):
if i<=20:
print((data[i]))