2、请自己查询open、write、os.mkdir命令,用try …except…语句完成下列功能: 如果存在 D:/test_file 文件夹,新建一个名为 test 的记事本文件,并在里面输入‘交个朋友’的字符串。 如果文件夹不存在,那就新建一个 D:/test_file 文件夹,然后新建一个名为 test 的记事本文件,并在里面输入‘不挣钱’的字符串。 程序保存为Chapter2_Exercises.py的第2个模块(cell)。
时间: 2023-05-18 10:07:05 浏览: 104
以下是代码实现:
```python
import os
try:
# 尝试打开 D:/test_file 文件夹
os.mkdir('D:/test_file')
except FileExistsError:
# 如果文件夹已经存在,什么也不做
pass
# 打开 test.txt 文件,如果不存在则创建
with open('D:/test_file/test.txt', 'w') as f:
if os.path.exists('D:/test_file/test.txt'):
# 如果文件已经存在,清空文件内容
f.truncate(0)
f.seek(0)
else:
# 如果文件不存在,创建文件
f = open('D:/test_file/test.txt', 'w')
# 写入字符串
f.write('交个朋友' if os.path.exists('D:/test_file') else '不挣钱')
```
注意:这段代码需要在 Windows 系统上运行,因为路径中使用了 Windows 的文件夹分隔符 `\`。如果在 Linux 或 macOS 上运行,需要将路径中的 `\` 替换为 `/`。
相关问题
try: os.mkdir(params.plot_dir) except FileExistsError: pass
这段代码的作用是创建一个名为params.plot_dir的目录,如果该目录已经存在,则忽略该操作,不会引发异常。其中,params.plot_dir是一个参数变量,用于存储目录路径。如果该目录不存在,os.mkdir(params.plot_dir)会创建一个新的目录。如果该目录已经存在,os.mkdir(params.plot_dir)会引发FileExistsError异常,该异常会被捕获并忽略,程序会继续执行。因此,通过在try语句块中调用os.mkdir(params.plot_dir),可以避免在目录已经存在时引发异常。
客户端使用Shell命令完成以下功能,判断HDFS是否存在/Test目录,如果不存在,则创建/Test目录
可以使用以下Shell脚本来实现:
```
#!/bin/bash
hadoop fs -test -d /Test
if [ $? -ne 0 ]; then
hadoop fs -mkdir /Test
echo "Directory /Test created."
else
echo "Directory /Test already exists."
fi
```
该脚本首先使用`hadoop fs -test -d`命令来判断`/Test`目录是否存在,如果返回值不为0,则说明目录不存在,此时使用`hadoop fs -mkdir`命令来创建`/Test`目录,并输出"Directory /Test created.";否则,说明目录已经存在,输出"Directory /Test already exists."。