用python 创建一个名字为111的文件夹,在文件夹中创建a.txt和b.txt文件,向a.txt文件第一行写入a,第二行写入b,第三行写入 c,向b.txt文件第一行写入a1,第二行写入b1,第三行写入c1
时间: 2024-04-14 08:26:26 浏览: 15
好的,以下是使用Python创建文件夹并创建文件、写入内容的代码:
```python
import os
# 创建文件夹
folder_name = '111'
os.makedirs(folder_name, exist_ok=True)
# 创建a.txt并写入内容
with open(os.path.join(folder_name, 'a.txt'), 'w') as file:
file.write('a\n')
file.write('b\n')
file.write('c\n')
# 创建b.txt并写入内容
with open(os.path.join(folder_name, 'b.txt'), 'w') as file:
file.write('a1\n')
file.write('b1\n')
file.write('c1\n')
print('文件夹和文件创建成功!')
```
运行以上代码后,会在当前目录下创建一个名为 "111" 的文件夹,其中包含了 "a.txt" 和 "b.txt" 两个文件。同时,会向 "a.txt" 写入三行内容:"a"、"b" 和 "c",向 "b.txt" 写入三行内容:"a1"、"b1" 和 "c1"。
相关问题
python,生成一个文件夹,将a.csv和b.csv和c.csv文件和d.txt文件放进生成的文件夹
可以使用Python的os模块和shutil模块来实现这个任务,代码如下:
```python
import os
import shutil
# 创建文件夹
folder_name = "my_folder"
os.mkdir(folder_name)
# 将文件移动到文件夹中
shutil.move("a.csv", folder_name)
shutil.move("b.csv", folder_name)
shutil.move("c.csv", folder_name)
shutil.move("d.txt", folder_name)
```
这段代码会在当前目录下创建一个名为"my_folder"的文件夹,并将"a.csv"、"b.csv"、"c.csv"和"d.txt"这四个文件移动到该文件夹中。
用python 遍历创建名字为1,2,3,...,33 的文件夹,在文件夹中创建a.txt和b.txt文件,向a.txt文件第一行写入a,第二行写入b,第三行写入 c,向b.txt文件第一行写入a1,第二行写入b1,第三行写入c1
可以使用以下代码来实现你的需求:
```python
import os
# 遍历创建文件夹
for i in range(1, 34):
folder_name = str(i)
os.makedirs(folder_name)
# 创建a.txt文件并写入内容
with open(os.path.join(folder_name, 'a.txt'), 'w') as file_a:
file_a.write('a\n')
file_a.write('b\n')
file_a.write('c\n')
# 创建b.txt文件并写入内容
with open(os.path.join(folder_name, 'b.txt'), 'w') as file_b:
file_b.write('a1\n')
file_b.write('b1\n')
file_b.write('c1\n')
```
这段代码使用`os.makedirs()`函数来创建文件夹。然后使用`with open()`语句来创建和打开文件,并使用`write()`方法向文件写入内容。`os.path.join()`函数用于构建文件路径,确保在不同操作系统上都能正确工作。通过使用循环,可以遍历创建名字为1到33的文件夹,并在每个文件夹中创建a.txt和b.txt文件,并向这两个文件中写入指定的内容。