Python Forum
Printing file path of lift elements
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Printing file path of lift elements
#1
Say I generated a list of all the files in a specific directory, but instead of just the file names, I wanted to print the complete file path for each element into a .txt file. Is is possible to associate a file path with something that's now included in a list? I'm very much a novice, so apologies if this doesn't make sense.
Reply
#2
(Sep-27-2021, 12:44 PM)dyerlee91 Wrote: I'm very much a novice, so apologies if this doesn't make sense.
Yes it make sense,but you should give try with some code then you show some effort and easier to help.
Here a couple of examples using pathlib
import pathlib

lst = []
mydir = r'G:\div_code\answer\weather'
for file in pathlib.Path(mydir).iterdir():
    if file.is_file():
        lst.append(file.name)
>>> lst
['file_1_0_.txt', 'file_33.txt', 'key.ini', 'open_weather.py', 'to_zip.txt']
>>> 
>>> for file in lst:
...     print(f'{mydir}{file}')
...     
G:\div_code\answer\weatherfile_1_0_.txt
G:\div_code\answer\weatherfile_33.txt
G:\div_code\answer\weatherkey.ini
G:\div_code\answer\weatheropen_weather.py
G:\div_code\answer\weatherto_zip.txt
So over generate absolute path for files in the list.

If remove .name then get absolute path with one go.
import pathlib

lst = []
mydir = r'G:\div_code\answer\weather'
for file in pathlib.Path(mydir).iterdir():
    if file.is_file():
        lst.append(file)
>>> lst
[WindowsPath('G:/div_code/answer/weather/file_1_0_.txt'),
 WindowsPath('G:/div_code/answer/weather/file_33.txt'),
 WindowsPath('G:/div_code/answer/weather/key.ini'),
 WindowsPath('G:/div_code/answer/weather/open_weather.py'),
 WindowsPath('G:/div_code/answer/weather/to_zip.txt')]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Fastest way to subtract elements of datasets of HDF5 file? Robotguy 3 2,635 Aug-01-2020, 11:48 PM
Last Post: scidam
  Formula with elements of list - If-condition regarding the lists elements lewielewis 2 2,735 May-08-2020, 01:41 PM
Last Post: nnk
  Checking the elements of a matrix with an elements of a list juniorcoder 11 5,858 Sep-17-2018, 03:02 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020