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:UsersHendreOneDriveDocumentsCourseWorkProjectPlayers
Code:
for files in Players: addPlayer = #first line of file self.playerlist.addItem(addPlayer)
Advertisement
Answer
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)