编写程序,在D盘根目录下创建一个文本文件test.txt,并向其中写入字符串“hello world”。
时间: 2024-02-13 10:01:29 浏览: 157
好的,下面是使用os库实现该功能的Python代码:
```python
import os
# 定义文件路径
file_path = 'D:/test.txt'
# 判断文件是否存在,如果存在则删除
if os.path.exists(file_path):
os.remove(file_path)
# 创建并打开文件
with open(file_path, 'w') as f:
# 向文件中写入内容
f.write('hello world')
```
这段代码首先使用os库中的`os.path.exists()`函数判断文件是否存在,如果存在则使用`os.remove()`函数删除文件。然后使用`open()`函数创建并打开文件,最后使用`write()`函数向文件中写入内容。运行该代码后,会在D盘根目录下创建一个名为test.txt的文本文件,并向其中写入字符串“hello world”。
相关问题
1、编写程序,在D盘根目录下创建一个文本文件test.txt,并向其中写入字符串hello world。
可以使用Python内置的文件操作函数来创建文件并写入字符串,以下是一个实现示例:
```python
filename = 'D:/test.txt'
with open(filename, 'w') as f:
f.write('hello world')
```
上述代码中,我们指定文件名为`'D:/test.txt'`,打开文件后以写模式`'w'`写入字符串`'hello world'`。在使用完文件后,使用`with`语句确保文件被关闭。执行完上述代码后,文件`test.txt`将被创建在D盘根目录下,并包含字符串`hello world`。
python 编写程序,在D盘根目录下创建一个文本文件test.txt,并向其中写入字符串“hello world
你可以使用Python的内置库`os`和`open`来实现:
```python
import os
# 定义文件路径
file_path = r"D:\test.txt"
# 判断文件是否存在,如果不存在则创建
if not os.path.isfile(file_path):
open(file_path, 'w').close()
# 向文件写入字符串
with open(file_path, 'w') as f:
f.write("hello world")
```
这段代码首先定义了文件路径,然后使用`os.path.isfile()`函数判断文件是否存在,如果不存在,则使用`open()`函数创建一个空文件。最后,使用`with open() as f:`语句打开文件,并使用`write()`方法向文件中写入字符串。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)