you should look at: https://pymotw.com/3/pathlib/
a pathlib path is much easier to construct if the path nodes are contained
within a list:
a pathlib path is much easier to construct if the path nodes are contained
within a list:
from pathlib import Path mylocation = ['..', 'data', 'fipsCodes', 'GNIScodesForNamedPopulatedPlaces-etc', 'CountryNames', 'geonames_20171023', 'Countries.txt'] home = Path('.') print('\n-- home --') print(f'{home}') print(f'{home.name}') print(f'{home.resolve()}') print('\n-- mydatapath --') mydatapath = home.joinpath(*mylocation) print(f'(\n{mydatapath}') print(f'({mydatapath.name}') print(f'{mydatapath.resolve()}') print('\n-- newdatapath --') # you can also create a path like newdatapath = home / 'data' print(f'\n{newdatapath}') print(f'{newdatapath.name}') print(f'{newdatapath.resolve()}') print('\n-- filelist --') filelist = [x.name for x in newdatapath.iterdir() if x.is_file()] print(f'\n{filelist}') print('\n-- opening files --') fips_text_file = newdatapath / 'fips.txt' with fips_text_file.open() as f: count = 0 for line in f: line = line.strip() count += 1 print(line) if count > 10: breakresults (part of resolved path removed for security, replaced with ...):
Output:-- home --
.
... \Tiger\src
-- mydatapath --
(
..\data\fipsCodes\GNIScodesForNamedPopulatedPlaces-etc\CountryNames\geonames_20171023\Countries.txt
(Countries.txt
... \Tiger\data\fipsCodes\GNIScodesForNamedPopulatedPlaces-etc\CountryNames\geonames_20171023\Countries.txt
-- newdatapath --
data
data
... \Tiger\src\data
-- filelist --
['fips.json', 'fips.txt', 'fipsdata.db', 'fipsdataBackup.db', 'FIPSFormat.json', 'FIPSFormat.txt', 'GNIS_CountryFormat.json', 'GNIS_CountryFormat.txt', 'GNIS_DomesticFormat.json', 'GNIS_DomesticFormat.txt']
-- opening files --
{
"AmericanIndianAreas": {
"data": {
"0010": [
"0010",
"Acoma Pueblo and Off-Reservation Trust Land"
],
"0020": [
"0020",
"Agua Caliente Indian Reservation and Off-Reservation Trust Land"
],