Home > Software design >  Collect data from multiple files in a folder and save it as a variable
Collect data from multiple files in a folder and save it as a variable

Time:05-04

I want to collect the data from the first line in each .txt file, all the files are in the same folder. I then want to save it in the variable: (addPlayer) This will be needed to add items to a pqt5 list Folder directory: C:\Users\Hendre\OneDrive\Documents\CourseWorkProject\Players

Code:

for files in Players:
    addPlayer = #first line of file
    self.playerlist.addItem(addPlayer)

CodePudding user response:

I think that will help you

import os
folder_path = "path to folder with files"
#folder_path = os.getcwd() #put your script in folder with files, then it return it's path

# that returns all .txt files pathes
Players = [file for file in os.listdir(folder_path) if file.endswith('.txt')]

addPlayer = list()

for files in Players:
    with open(files, 'r') as f:
        line_data = f.readline()
    #if in files are more then one line
    line_data = line_data.replace("\n", "")
    addPlayer.append(line_data)
  • Related