Python 写文件
时间: 2024-01-07 07:05:45 浏览: 23
以下是Python写文件的两种方法:
1. 使用open()函数打开文件,然后使用write()方法写入内容,最后使用close()方法关闭文件。
```python
file = open('example.txt', 'w')
file.write('This is an example.\n')
file.write('Python is a great language.\n')
file.close()
```
2. 使用with语句打开文件,这种方法可以自动关闭文件,不需要手动调用close()方法。
```python
with open('example.txt', 'w') as file:
file.write('This is an example.\n')
file.write('Python is a great language.\n')
```
相关问题
python 写文件
以下是Python写文件的示例代码:
```python
# 打开文件,如果文件不存在则创建新文件
file = open("example.txt", "w")
# 写入内容到文件
file.write("Hello, World!")
# 关闭文件
file.close()
```
这段代码首先使用`open()`函数打开一个名为"example.txt"的文件,并指定打开模式为写入模式("w")。如果文件不存在,则会创建一个新文件。然后,使用`write()`方法将字符串"Hello, World!"写入文件中。最后,使用`close()`方法关闭文件。
请注意,写入模式会覆盖文件中的所有内容。如果要在文件中追加内容而不是覆盖原有内容,可以使用追加模式("a")打开文件。
Python读写文件
Python提供了多种读写文件的方式,下面是其中几种常用的方法:
1. 使用`open()`函数打开文件:
```python
file = open("filename.txt", "mode")
```
其中,`filename.txt`是要打开的文件名,`mode`是打开文件的模式,常见的模式有:
- `"r"`:只读模式,用于读取文件内容(默认模式)。
- `"w"`:写入模式,用于清空文件内容并写入新内容。
- `"a"`:追加模式,用于在文件末尾追加内容。
- `"x"`:创建模式,用于创建新文件并写入内容。
- `"b"`:二进制模式,用于读写二进制文件。
- `"t"`:文本模式,用于读写文本文件(默认模式)。
2. 使用`read()`方法读取文件内容:
```python
content = file.read()
```
该方法将整个文件的内容读取为一个字符串,并赋值给变量`content`。
3. 使用`write()`方法写入文件内容:
```python
file.write("Hello, World!")
```
该方法将字符串`"Hello, World!"`写入文件。
4. 使用`close()`方法关闭文件:
```python
file.close()
```
在读写完文件后,应该使用该方法关闭文件,释放资源。
5. 使用`with`语句自动关闭文件:
```python
with open("filename.txt", "mode") as file:
# 在此处进行文件读写操作
```
使用`with`语句可以自动关闭文件,无需手动调用`close()`方法。