python 读取txt中的一列
时间: 2023-12-11 12:03:48 浏览: 316
你可以使用 Python 的内置函数 `open()` 和 `readlines()` 来读取文本文件中的内容。假设你要读取名为 `data.txt` 的文本文件中的第一列数据,可以按照以下步骤进行:
1. 打开文本文件并读取所有行:
```
with open('data.txt', 'r') as f:
lines = f.readlines()
```
2. 提取第一列数据:
```
first_column = [line.split()[0] for line in lines]
```
在这里,使用了列表推导式来提取每行数据的第一个单词,也就是第一列数据。
完整代码示例:
```
with open('data.txt', 'r') as f:
lines = f.readlines()
first_column = [line.split()[0] for line in lines]
print(first_column)
```
相关问题
使用python读取txt最后一列
可以使用以下代码读取txt文件的最后一列:
```
with open('file.txt', 'r') as f:
lines = f.readlines()
last_column = [line.split()[-1] for line in lines]
```
其中,`file.txt`是你要读取的txt文件名,`last_column`是最后一列的数据列表。
python读取TXT文件每一列
要使用Python读取TXT文件的每一列,可以使用以下代码示例中的任意一种方法:
方法一:
```python
import codecs
f = codecs.open('test.txt', mode='r', encoding='utf-8') # 打开txt文件,以‘utf-8'编码读取
line = f.readline() # 以行的形式进行读取文件
list1 = []
list2 = []
while line:
a = line.split()
b = a[2:3] # 这是选取需要读取的位数
c = a[2]
list1.append(b) # 将其添加在列表之中
list2.append(c)
line = f.readline()
f.close()
for i in list1:
print(i)
for i in list2:
print(i)
```
方法二:
```python
list1 = []
try:
file = open('test.txt', 'r')
except FileNotFoundError:
print('File is not found')
else:
lines = file.readlines()
for line in lines:
a = line.split()
x = a[4]
list1.append(x)
file.close()
for x in list1:
print(x)
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)