What I am trying to do is to make my program randomly pick a folder from a directory and read the slots.csv file inside. All of the folders have the slots.csv file, it's just that the folders are named differently. I understand how to use random.choice(os.listdir("C:\\"))
but I can't seem to get it to work with folders...
import os, random
random_centre = random.choice(os.listdir("Centres" "\\" postcode))
df = pandas.read_csv(r"Centres" "\\" postcode "\\" random_centre "\\" "slots.csv")
I keep getting the same error,
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'Centres\\31400'
CodePudding user response:
I don't have Pandas, so here's a mock-up using Python's CSV module.
My number-one suggestion is to use os.path.join()
for assembling your paths. Even though I'm on a Mac, this code should work on your Windows machine because the join()
method takes the OS into consideration when picking the path separator. That's probably not your issue, but it'll make your code a little cleaner.
As for the random question, your code looks like it should work:
import csv
import os
import random
postcode = '12345'
base_path = os.path.join('Centres', postcode)
random_centre = random.choice(os.listdir(base_path))
csv_path = os.path.join(base_path, random_centre, 'slots.csv')
with open(csv_path, newline='') as f:
reader = csv.reader(f)
print(csv_path)
print(list(reader))
Here's what it looks like when I run this a couple of times:
% ./main.py
Centres/12345/b/slots.csv
[['Col1', 'Col2'], ['Val1', 'Val2']]
% ./main.py
Centres/12345/a/slots.csv
[['Col1', 'Col2'], ['Val3', 'Val4']]
% ./main.py
Centres/12345/a/slots.csv
[['Col1', 'Col2'], ['Val3', 'Val4']]
% ./main.py
Centres/12345/b/slots.csv
[['Col1', 'Col2'], ['Val1', 'Val2']]
% ./main.py
Centres/12345/a/slots.csv
[['Col1', 'Col2'], ['Val3', 'Val4']]
% ./main.py
Centres/12345/c/slots.csv
[['Col1', 'Col2'], ['Val5', 'Val6']]