python,创建Total Result文件夹,如果不存在就创建并将文件a.csv、b.csv、result.txt存放进去,存在更换名字创建新的文件夹并将文件a.csv、b.csv、result.txt存放进去。
时间: 2024-05-10 15:20:23 浏览: 9
以下是Python代码:
```python
import os
# 指定文件夹名称
folder_name = "Total Result"
# 检查文件夹是否存在
if not os.path.exists(folder_name):
# 如果不存在,创建文件夹
os.mkdir(folder_name)
else:
# 如果存在,更换文件夹名称并创建新的文件夹
i = 1
while True:
new_folder_name = folder_name + " " + str(i)
if not os.path.exists(new_folder_name):
os.mkdir(new_folder_name)
folder_name = new_folder_name
break
i += 1
# 将文件a.csv、b.csv、result.txt存放到文件夹中
with open(os.path.join(folder_name, "a.csv"), "w") as f:
f.write("This is file a.csv")
with open(os.path.join(folder_name, "b.csv"), "w") as f:
f.write("This is file b.csv")
with open(os.path.join(folder_name, "result.txt"), "w") as f:
f.write("This is file result.txt")
```
在这个代码中,我们首先指定了要创建的文件夹的名称为"Total Result"。然后,我们使用`os.path.exists()`函数检查该文件夹是否存在。如果不存在,我们使用`os.mkdir()`函数创建该文件夹。如果存在,我们通过迭代更改文件夹名称,直到找到一个不存在的文件夹名称为止。然后,我们使用`open()`函数和`write()`方法将文件a.csv、b.csv和result.txt写入到新创建的文件夹中。我们使用`os.path.join()`函数来创建文件路径,该函数将文件夹名称和文件名组合在一起,以便正确地将文件存放在文件夹中。