0

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)
  • This should answer your question: [Read only the first line of a file?](https://stackoverflow.com/questions/1904394/read-only-the-first-line-of-a-file) – Marco Bonelli May 03 '22 at 18:41

1 Answers1

1

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)
Bogdan M.
  • 41
  • 3