Python文件如何读取文件
时间: 2023-11-05 07:10:39 浏览: 122
Python提供了多种读取文件的方式,常见的有以下几种:
1. 使用`open()`函数打开文件并读取内容:
```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.strip())
```
3. 读取指定行数的内容:
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
for i in range(5):
print(lines[i])
```
4. 使用`csv`模块读取CSV文件:
```python
import csv
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row)
```
5. 使用`pandas`模块读取Excel文件:
```python
import pandas as pd
df = pd.read_excel('file.xlsx')
print(df)
```
相关问题
python 文件读写
在Python中,要读写文件,可以使用内置的`open()`函数。
### 读文件
要打开一个文件并读取其中的内容,可以使用`open()`函数,并指定文件名和打开模式。例如,要以只读模式打开一个名为`example.txt`的文件,可以这样做:
```python
f = open('example.txt', 'r')
```
然后,可以使用`read()`方法读取文件中的内容:
```python
content = f.read()
```
读取完文件后,需要关闭文件:
```python
f.close()
```
完整的代码如下:
```python
f = open('example.txt', 'r')
content = f.read()
f.close()
print(content)
```
### 写文件
要写入文件,可以使用模式为`w`的`open()`函数。例如,要写入一个名为`example.txt`的文件,可以这样做:
```python
f = open('example.txt', 'w')
```
然后,可以使用`write()`方法写入内容:
```python
f.write('Hello, world!')
```
写入完文件后,需要关闭文件:
```python
f.close()
```
完整的代码如下:
```python
f = open('example.txt', 'w')
f.write('Hello, world!')
f.close()
```
注意:在使用`w`模式打开文件时,如果文件不存在,Python会自动创建该文件。如果文件已存在,Python会覆盖原有内容。如果需要在已有内容后面继续添加内容,可以使用模式为`a`的`open()`函数。
Python文件读写
以下是Python文件读写的两种方法示例:
1. 使用read方法读取文件内容:
```python
file = open('itheima.txt', 'r')
content = file.read(12) # 读取文件前12个字符
print(content)
print("-" * 30)
content = file.read() # 继续读取文件剩余内容
print(content)
file.close()
```
2. 使用readline方法逐行读取文件内容:
```python
file = open('itheima.txt', 'r')
content = file.readline() # 读取文件的第一行
print("1:%s" % content)
content = file.readline() # 读取文件的第二行
print("2:%s" % content)
file.close()
```
阅读全文
相关推荐












