如何在python中导入同时包含值和文本的文本文件?

2024-05-16 00:48:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道在这个话题上已经有很多问题被问到了,但是没有一个问题适用于我的具体案例

我想在python中导入一个文本文件,并希望能够在python中分别访问每个值。我的文本文件看起来像(它由制表符分隔): example dataset

例如,数据“1086:CampNou”写在一个单元格中。我主要感兴趣的是获得这里介绍的价值观。有人知道怎么做吗

1086:CampNou 2084:Hospi 2090:Sants 2094:BCN-S 2096:BCN-N 2101:UNI 2105:B23总计 1086:坎普努0 156508 125812 303729 502963 0 560408 164942 2084:医院157804 0 193732 371791 541852 274028 599297 213,85 2090:桑特128067 221304 0 306268 567759 299935 625204 214854 2096:电话:BCN-N 51135 548545 573742 460102 0 456746 568001 311849 2101:统一电话:0 289589 314786 375029 316773 0 502681 179886 2105:B23 511224385838 573634 751552 567478 402728 0 319247 总计130846 160178 178171 256847 249683 143344 285559 1404,63'


Tags: 数据exampledataset感兴趣制表符案例电话总计
2条回答
def read_file(filename):
    """Returns content of file"""
    file = open(filename, 'r')
    content = file.read()
    file.close()
    return content

content = read_file("the_file.txt") # or whatever your text file is called
items = content.split('    ')

那么您的值将在列表items['', '1086: CampNou', '2084: Hospi', '2090: Sants', ...]

您可以使用熊猫来打开和操作数据

import pandas as pd 

df = pd.read_csv("mytext.txt")

这应该能正确读取你的文件

相关问题 更多 >