从文件夹中的多个文件中收集数据并将其保存为变量
Collect data from multiple files in a folder and save it as a variable
我想从每个 .txt 文件的第一行收集数据,所有文件都在同一个文件夹中。然后我想将它保存在变量中:(addPlayer)
这将需要将项目添加到 pqt5 列表
文件夹目录:C:\Users\Hendre\OneDrive\Documents\CourseWorkProject\Players
代码:
for files in Players:
addPlayer = #first line of file
self.playerlist.addItem(addPlayer)
我想这对你有帮助
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)
我想从每个 .txt 文件的第一行收集数据,所有文件都在同一个文件夹中。然后我想将它保存在变量中:(addPlayer) 这将需要将项目添加到 pqt5 列表 文件夹目录:C:\Users\Hendre\OneDrive\Documents\CourseWorkProject\Players
代码:
for files in Players:
addPlayer = #first line of file
self.playerlist.addItem(addPlayer)
我想这对你有帮助
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)