[Tutor] Still not understanding passing filenames in Python
boB Stepp
robertvstepp at gmail.com
Sat Jun 6 21:47:43 EDT 2020
Now in "3.4 Modules" at
https://dabeaz-course.github.io/practical-python/Notes/03_Program_organization/04_Modules.html
Earlier in the course I wrote a program, report.py, that runs as so:
bob at Dream-Machine1:~/practical-python/Work$ python3 report.py
Enter path to portfolio file: Data/portfolio.csv
Enter path to stock prices file: Data/prices.csv
Name Shares Price Change
---------- ---------- ---------- ----------
AA 100 $9.22 -22.98
IBM 50 $106.28 15.18
CAT 150 $35.46 -47.98
MSFT 200 $20.89 -30.34
GE 95 $13.48 -26.89
MSFT 50 $20.89 -44.21
IBM 100 $106.28 35.84
Current portfolio value = $28,686.10
Current portfolio gain/loss = $-15,985.05
In "Exercise 3.12: Using your library module" Beazley has us importing the
recently discussed fileparse module containing the parse_csv() function to
replace the code previously written in the read_portfolio() function in
report.py. So I added "import fileparse" and modified the read_portfolio()
function to:
def read_portfolio(filename: str) -> List[Dict[str, Union[str, int, float]]]:
"""Read a file and return a portfolio list of records."""
portfolio = fileparse.parse_csv(
filename, select=["name", "shares", "price"], types=[str, int, float]
)
return portfolio
report.py and fileparse.py are both in the same Work directory. Data is a
subdirectory of Work.
But when I try to run this program with the same file location entries
I get:
bob at Dream-Machine1:~/practical-python/Work$ python3 report.py
Enter path to portfolio file: Data/porfolio.csv
Enter path to stock prices file: Data/prices.csv
Traceback (most recent call last):
File "report.py", line 113, in <module>
main()
File "report.py", line 104, in main
portfolio = read_portfolio(portfolio_path)
File "report.py", line 18, in read_portfolio
filename, select=["name", "shares", "price"], types=[str, int, float]
File "/home/bob/practical-python/Work/fileparse.py", line 25, in parse_csv
with open(filename) as fileobj:
FileNotFoundError: [Errno 2] No such file or directory: 'Data/porfolio.csv'
If I use absolute file paths, "/home/bob/practical-python..." it works.
If I use "./Data/portfolio.csv" and "./Data/prices.csv" it works. I
currently do not understand the differences. Obviously I do understand one
or more things. A helpful explanation please? Thanks!
--
Wishing you only the best,
boB Stepp
More information about the Tutor
mailing list