I have a directory of 50 txt files. I want to combine the contents of each file into a Python list.
Each file looks like;
line1
line2
line3
I am putting the files / file path into a list with this code. I just need to loop through file_list
and append the content of each txt file to a list.
from pathlib import Path
def searching_all_files():
dirpath = Path(r'C:\num')
assert dirpath.is_dir()
file_list = []
for x in dirpath.iterdir():
if x.is_file():
file_list.append(x)
elif x.is_dir():
file_list.extend(searching_all_files(x))
return file_list
But I am unsure best method
Maybe loop something close to this?
NOTE: NOT REAL CODE!!!! JUST A THOUGHT PULLED FROM THE AIR. THE QUESTION ISNT HOW TO FIX THIS. I AM JUST SHOWING THIS AS A THOUGHT. ALL METHODS WELCOME.
file_path = Path(r'.....')
with open(file_path) as f:
source_path = f.read().splitlines()
source_nospaces = [x.strip(' ') for x in source_path]
return source_nospaces