How do I get the file name and values I am getting form a file into a dataframe python

I am looking to read more than one file that starts with access-team then after I read the files I access them and get the information after username = and put it into a dataframe having a username and filename associated to
Here is the code I currently have but doesn’t it doesn’t dot it all yet. I am not sure how to read the two files and incorporate them into what I have below. my current results for one file are in one column. I need the dataframe to have the username and the file name.
file name: access-team-rev.txt file two is same way to but it is called access-team-support.txt
files look like this:

How do I get the file name and values I am getting form a file into a dataframe python

import re
filename = 'access-team-rev.txt'
pattern = re.compile(r'usernames=s(w+)')
l = [] 
with open(filename, "rt") as myfile:
    for line in myfile:
        if pattern.search(line) != None:
            l.append(line.strip('username = ')) 
            l.append(filename.strip('.txt'))

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You should append as list

l.append( [ line.strip('username = '), filename.strip('.txt')] )

and after for-loop you can do

df = pandas.DataFrame(l)

and you will have it in DataFrame


Minimal working code

import pandas as pd

l = []

l.append( ['user1','file1'] )
l.append( ['user2','file2'] )

df = pd.DataFrame(l, columns=['username', 'filename'])

print(df)

Result

  username filename
0    user1    file1
1    user2    file2

EDIT:

Read data

import re

filename = 'access-team-rev.txt'
pattern = re.compile(r'usernames=s(w+)')

l = [] 

with open(filename) as myfile:
    for line in myfile:
        if pattern.search(line):
            l.append( [ line.strip('username = '), filename.strip('.txt')] )


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x