共翁号
共翁号 > 科普 > python如何读取txt文件

python如何读取txt文件

原创2025-06-20 18:17:40

在Python中,读取txt文件可以通过以下几种方法:

1. 使用`open()`函数和`read()`方法:

```python

with open('file.txt', 'r', encoding='utf-8') as file:

content = file.read()

print(content)

```

2. 使用`with`语句和`read()`方法:

```python

with open('file.txt', 'r', encoding='utf-8') as file:

content = file.read()

print(content)

```

3. 使用`with`语句和`readlines()`方法:

```python

with open('file.txt', 'r', encoding='utf-8') as file:

lines = file.readlines()

for line in lines:

print(line.strip())

```

4. 使用`with`语句和逐行读取:

```python

with open('file.txt', 'r', encoding='utf-8') as file:

for line in file:

print(line.strip())

```

请确保在打开文件时指定正确的文件路径和编码方式,如`encoding='utf-8'`。如果文件不存在或无法读取,程序将抛出异常。使用`with`语句可以确保文件在使用完毕后自动关闭,无需手动调用`close()`方法

返回:科普

相关阅读

    最新文章
    猜您喜欢
    热门阅读