Reputation: 21
I have a folder called data inside my python folder which is full of text files, each named a state's abbreviation ("NY", "CA", "RI", etc.). I need to take user input of the name of a state and then open that file.
I tried this:
file = ""
file = open("NY", "r").read().splitelines()
but it came up with nothing in the directory. How can I open individual files from the folder?
Upvotes: 2
Views: 253
Reputation: 5168
from os.path import join, dirname
data_dir = join(dirname(__file__), 'data')
with open(join(data_dir, raw_input('Enter state: '))) as f:
print(f.readlines())
This code makes a base dir variable and joins it with the state name. When executed you will see
brunsgaard@archbook ~/t/test> python test.py
Enter state: NY
['Hello, I am the NY file\n']
This example was run in the context of the following diretory structure.
.
├── data
│ └── NY
└── test.py
Upvotes: 2