python创建文件并写入
时间: 2023-07-14 20:10:36 浏览: 65
要在Python中创建文件并写入内容,你可以使用内置的`open()`函数。下面是一个示例代码:
```python
def create_and_write_file(file_name, content):
"""
创建文件并写入内容
参数:
file_name : 文件名(包括路径)
content : 要写入的内容
"""
with open(file_name, 'w') as file:
file.write(content)
```
使用该函数,你需要提供文件名(包括路径)以及要写入的内容。函数会自动创建指定的文件,并将内容写入其中。
例如,假设你想创建一个名为 `example.txt` 的文件,并将字符串 `"Hello, World!"` 写入其中,你可以使用以下代码:
```python
file_name = 'example.txt'
content = 'Hello, World!'
create_and_write_file(file_name, content)
```
运行上述代码后,将会在当前目录下创建一个名为 `example.txt` 的文件,并将字符串 `"Hello, World!"` 写入其中。
请注意,如果指定的文件已经存在,`'w'` 模式会覆盖原有内容,并从头开始写入新的内容。如果你希望追加内容而不是覆盖,请使用 `'a'` 模式打开文件。例如,将 `with open(file_name, 'w') as file:` 修改为 `with open(file_name, 'a') as file:`。这样每次运行代码时,新的内容都会追加到文件末尾。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)