需要使用python逐行读取文本文件并将用户数据放入pandas数据框

时间:2019-03-01 16:25:11

标签: python-3.x

我需要使用python逐行读取文本文件,并将用户数据放入pandas数据框

我在下面尝试过

import pandas as pd
y=0
Name =[]
Age =[]
with open('file.txt', 'r') as fp:
    for line in fp:
        if line =="<USERDATA":
            row=True
            break
        else:
            l = line.split("=")[0]
            i = line.split("=")[-1]
            row=False

        if row == False:
            if "\tName" in l:
                Name.append(i)
        elif "\Age" in l:
                Age.append(i)

        else:
              pass
     else:
        pass

        while 0<=y<(len(Name))-1:

        z={"Name":Nmae[y],"Age":Age[y]}

        y += 1


df = pd.DataFrame(z,columns=["Name","Age"],index=None)

文件内容如下所示: sample

1 个答案:

答案 0 :(得分:0)

您遇到了一些逻辑问题,我们已经解决了这些问题,我鼓励您将您的代码与我的代码进行比较,然后尝试查看存在的差异,如果您有任何疑问,请在下面评论。

import pandas as pd
import numpy as np
y=0
Name =[]
Age =[]
z={}
with open('file.txt', 'r') as fp:
    for line in fp:
        line = line.strip()
        if line ==r'<USERDATA':
            row=True
            continue
        if line ==r'<USEREND':
            if (len(Age)<len(Name)):
                Age.append(np.nan) #only adding once since done at end of each row
            elif (len(Name)<len(Age)):
                Name.append(np.nan)
            continue
        else:
            l = line.split("=")[0].strip()
            i = line.split("=")[-1].strip()
            row=False
        if row == False:
            if l == 'Name':
                Name.append(i)
            elif l == 'Age':
                Age.append(i)
        z={"Name":Name,"Age":Age}
df = pd.DataFrame(z,columns=["Name","Age"],index=None)