python将str写入txt文件中,没有文件则自动创建
时间: 2023-05-11 12:06:06 浏览: 451
可以使用以下代码将字符串写入txt文件中:
```
with open('filename.txt', 'w') as f:
f.write('your string here')
```
如果文件不存在,会自动创建一个新的文件。
相关问题
python使用os库将str写入txt文件中,没有文件则自动创建
可以使用以下代码将字符串写入txt文件中:
```python
import os
text = "这是要写入文件的字符串"
if not os.path.exists("example.txt"):
open("example.txt", "w").close()
with open("example.txt", "w") as f:
f.write(text)
```
如果文件不存在,则会自动创建一个名为"example.txt"的文件,并将字符串写入其中。
python将数值写入txt文件
可以使用Python内置的文件操作函数将数值写入txt文件。以下是一些示例代码:
```python
# 打开文件,如果文件不存在则创建它
file = open("data.txt", "w")
# 将数值写入文件
num = 123.456
file.write(str(num))
# 关闭文件
file.close()
```
在上面的代码中,我们使用了`open()`函数打开了一个名为`data.txt`的文件,并指定了`"w"`作为第二个参数,表示我们要以写入模式打开文件。如果文件不存在,则会创建一个新文件。
接着,我们将数值`123.456`转换成字符串并使用`write()`函数将其写入文件中。
最后,我们使用`close()`函数关闭文件。这很重要,因为它确保了在我们完成写入后,文件被正确地保存和关闭。
可以通过打开`data.txt`文件来验证是否成功将数值写入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)