Python+file
时间: 2024-01-12 21:05:44 浏览: 62
python file
Python中的文件操作可以通过内置的`open()`函数来实现。`open()`函数接受两个参数:文件名和打开模式。打开模式可以是只读、只写、追加等等。默认情况下,`open()`函数以只读模式打开文件。
以下是一些常见的文件操作:
1. 打开文件并读取内容
```python
with open('file.txt', 'r') as f:
content = f.read()
print(content)
```
2. 打开文件并逐行读取内容
```python
with open('file.txt', 'r') as f:
for line in f:
print(line)
```
3. 打开文件并写入内容
```python
with open('file.txt', 'w') as f:
f.write('Hello, world!')
```
4. 打开文件并追加内容
```python
with open('file.txt', 'a') as f:
f.write('Hello, world!')
```
5. 打开二进制文件并读取内容
```python
with open('file.bin', 'rb') as f:
content = f.read()
print(content)
```
6. 打开二进制文件并写入内容
```python
with open('file.bin', 'wb') as f:
f.write(b'\x48\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72\x6c\x64\x21')
```
阅读全文