编写/root/createfile.py 的 python3 脚本,创建 20 个文件 /root/python/file00至/root/python/file19,如果文件存在,则删除后再创建; 每个文件的内容同文件名,如 file00 文件的内容为“file00”。
时间: 2023-12-08 19:04:13 浏览: 21
以下是创建和删除文件的Python脚本:
```python
import os
folder_path = '/root/python'
os.makedirs(folder_path, exist_ok=True)
for i in range(20):
file_path = f'{folder_path}/file{str(i).zfill(2)}'
content = f'file{str(i).zfill(2)}'
if os.path.exists(file_path):
os.remove(file_path)
with open(file_path, 'w') as file:
file.write(content)
```
请确保你有足够的权限来执行这些操作,并且目标目录`/root/python`存在。该脚本会在指定目录下创建20个文件,并且每个文件的内容与文件名相同。如果文件已经存在,则会先删除再重新创建。
相关问题
在linux4上编写/root/createfile.py的python3脚本,创建20个文件/root/python/file00至/root/python/file19,如果文件存在,则删除再创建;每个文件的内容同文件名,如file00文件的内容为“file00”。
您可以使用以下Python脚本在Linux上创建文件:
```python
import os
# 检查目录是否存在,如果不存在则创建
directory = '/root/python'
if not os.path.exists(directory):
os.makedirs(directory)
# 创建文件
for i in range(20):
filename = f'/root/python/file{i:02d}'
content = f'file{i:02d}'
if os.path.exists(filename):
os.remove(filename)
with open(filename, 'w') as file:
file.write(content)
```
将上述代码保存到 `/root/createfile.py` 文件中,然后在Linux终端中运行以下命令以执行脚本:
```bash
python3 /root/createfile.py
```
这将创建名为 `file00` 到 `file19` 的20个文件,并将它们放在 `/root/python` 目录下。如果文件已经存在,则会先删除再创建。每个文件的内容与文件名相同。
编写/root/createfile.sh的shell脚本,创建20个文件/root/shell/file00至/root/shell/file19,如果文件存在,则删除再创建;每个文件的内容同文件名,如file00文件的内容为“file00”。用/root/createfile.sh命令测试。
你可以使用以下脚本来创建和删除文件:
```shell
#!/bin/bash
# 创建目录(如果不存在)
mkdir -p /root/shell
# 遍历创建文件
for ((i=0; i<20; i++)); do
file="/root/shell/file$(printf "%02d" $i)"
content="file$(printf "%02d" $i)"
# 如果文件存在,则删除
if [ -f "$file" ]; then
rm "$file"
fi
# 创建文件并写入内容
echo "$content" > "$file"
done
```
将以上脚本保存为 `/root/createfile.sh`,然后在终端中运行以下命令进行测试:
```shell
chmod +x /root/createfile.sh # 添加执行权限
/root/createfile.sh # 运行脚本创建文件
```
这将会在 `/root/shell` 目录下创建 20 个文件,每个文件的名称为 `file00` 至 `file19`,并且内容与文件名相同。如果文件已经存在,则会先删除再创建。