遍历文件夹,并找到以csv结尾的csv文件, 根据csv文件建立相应的文件夹。并在文件夹里创建1.txt的文件。下面代码可以参考
for root,dirs,files in os.walk(dataPath):
for file in files:
#获取文件所属目录
print(root)
#获取文件路径
print(os.path.join(root,file))
if file.endswith('csv'):
print(os.path.join(root,file))
path = os.path.join(root, file)
os.mkdir(path, mode=0o777)
最开始是这样,
然后达到这样
你题目的解答代码如下:
import os
dataPath = r"e:/xxx"
for root,dirs,files in os.walk(dataPath):
for file in files:
#获取文件所属目录
print(root)
#获取文件路径
print(os.path.join(root,file))
if file.endswith('.csv'):
print(os.path.join(root,file))
path = os.path.join(root, file.replace(".csv",""))
if not os.path.exists(path): # 如果不存在则创建目录
os.makedirs(path) # 创建目录操作函数
textpath = os.path.join(path,"1.txt")
print(textpath)
with open(textpath, 'w', encoding='utf-8') as fileObj:
fileObj.write("文件内容")
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!