简体   繁体   中英

How can I include the results of reading parts of a txt into a dataframe in python?

I am working with a long txt file, of which I have the structure, and need the positions on the code below (form every line) in a list, so I can put them into a data frame and work with them:

with open('File.txt','r') as file:
lines = file.readlines()
for line in lines:
    a,b = 0,2
    c,d= 2,19
    e,f= 44,52
    g,h= 52,64
 print(line[a:b],line[c:d],line[e:f],line[g:h])

The results come out right in the print() above, but I cannot seem to put it into a list with the following code:

list([line[a:b],line[c:d],line[e:f],line[g:h]])

The result of the prior code is just a list with all the correct positions but only of the very last line on my data

Remove the print statement..

list((line[a:b],line[c:d],line[e:f],line[g:h]))

or

[line[a:b],line[c:d],line[e:f],line[g:h]]

for your comment:

with open('File.txt', 'r') as file:
    lines = file.readlines()
    your_list = []
    a, b = 0, 2
    c, d = 2, 19
    e, f = 44, 52
    g, h = 52, 64

    for line in lines:
        your_list.append([line[a:b], line[c:d], line[e:f], line[g:h]])
import pandas as pd
a, b = 0, 2
c, d = 2, 19
e, f = 44, 52
g, h = 52, 64

##### Read the text file
with open(r"File.txt","r") as file:
    lines = file.readlines()    

##### Convert the text data to Dataframe
df = pd.DataFrame([[line[a:b], line[c:d], line[e:f], line[g:h]] for line in lines])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM