'Convert items in python list to paths
I have a python list which I need to make changes to the items Here's my code till now
from pathlib import Path
BASE_DIR = Path.cwd()
MAIN_DIR = BASE_DIR / 'Files'
mylist = ['6', '112318', '112319']
# outputlist = ['C:\\Users\\Future\\Desktop\\Files\\112318.pdf', 'C:\\Users\\Future\\Desktop\\Files\\112319.pdf']
So the first item is to be skipped and the other items to be converted to be as paths for pdf files in Files directory.
@Daweo This is my attempt (can you please have a look and give me your review)
mylist = ['1', '112238', '112239', '112240', '112337', '165222', '112338']
files_list = [MAIN_DIR / f'{i}.pdf' for i in mylist[1:]]
final_list = []
final_list.append(mylist[0])
for file in files_list:
if file.exists():
final_list.append(file)
else:
print(f'{file} ---> NOT Exists')
print('=' * 50)
print(final_list)
Solution 1:[1]
I would do it following way from pathlib import Path
MAIN_DIR = Path("C:\\Users\\Future\\Desktop\\Files")
mylist = ['6', '112318', '112319']
outputlist = [MAIN_DIR / f'{i}.pdf' for i in mylist[1:]]
print(outputlist)
Output
[WindowsPath('C:/Users/Future/Desktop/Files/112318.pdf'), WindowsPath('C:/Users/Future/Desktop/Files/112319.pdf')]
Note: for sake of example simplicity I elected to use fixed MAIN_DIR. Features used: list slicing (to skip 1st element), f-string (for string formating, requires python3.6 or newer), list comprehension.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daweo |
