如何在python上新建文件
时间: 2024-05-09 19:14:19 浏览: 18
在Python中,可以使用内置的`open()`函数来创建新文件。下面是一个简单的示例代码:
```python
# 新建一个名为example.txt的文件并写入一些内容
with open('example.txt', 'w') as f:
f.write('Hello, world!')
```
这个代码将创建一个名为`example.txt`的新文件,并写入字符串`'Hello, world!'`到文件中。使用`with`语句可以确保文件在使用完后自动关闭,不需要手动调用`close()`方法。文件模式`'w'`表示写模式,如果文件不存在则会创建新文件,如果文件已经存在则会覆盖原有内容。如果想要追加内容到文件末尾而不是覆盖原有内容,可以使用文件模式`'a'`。
相关问题
怎么在Python中创建文件
在Python中创建文件可以使用内置函数open(),例如:
```
file = open("example.txt", "w")
```
其中,第一个参数是文件名,第二个参数是打开文件的模式,"w"表示写入模式。如果文件不存在,open()函数会自动创建一个新文件。
在python工程新建ini文件
要在Python工程中新建ini文件,可以使用configparser模块。以下是一个例子:
```python
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Port'] = '50022'
topsecret['ForwardX11'] = 'no'
with open('example.ini', 'w') as configfile:
config.write(configfile)
```
这段代码会创建一个名为example.ini的文件,并向其中写入一些配置信息。可以根据具体需要修改这些配置信息。
相关推荐
![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)