python读取txt文件的一到三列
时间: 2023-03-28 08:04:46 浏览: 149
可以使用Python中的pandas库来读取txt文件,并且只读取前三列数据。具体代码如下:
```python
import pandas as pd
# 读取txt文件,以空格分隔
df = pd.read_csv('file.txt', sep=' ', usecols=[,1,2])
# 打印前三行数据
print(df.head(3))
```
其中,`file.txt`是你要读取的txt文件名,`usecols=[,1,2]`表示只读取前三列数据。
相关问题
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)
```
python读取txt文件某一列
可以使用Python内置的open()函数和readlines()方法来读取txt文件的某一列。具体代码如下:
```python
with open('file.txt', 'r') as f:
lines = f.readlines()
column = [line.split()[0] for line in lines] # 假设要读取第一列
```
其中,'file.txt'是要读取的txt文件名,'r'表示以只读方式打开文件。readlines()方法将文件的每一行读取为一个字符串,并将这些字符串存储在一个列表中。接下来,我们可以使用列表推导式来提取出某一列的数据。上面的代码假设要读取第一列,因此使用了line.split()[0]来获取每一行的第一个元素。最终,column变量将包含txt文件中某一列的所有数据。
相关推荐
![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)