I am kinda new to programming, but I am trying to learn new things. So I decided to learn how to open csv files without libraries like panda. However the Python in command prompt is saying, that my file is not csv, but I am 100% sure it's csv, I've got it from our teacher.
from pathlib import Path
import sys
script_name = sys.argv[0]
argument = sys.argv[:1]
if len(argument) != 1:
print(f'Mistake! {script_name} <CSV_FILE>', file=sys.stderr)
exit(1)
input_file = Path(argument[0])
if not input_file.exists():
print('File does not exist!', file=sys.stderr)
exit(1)
if not input_file.is_file():
print('This is not file', file=sys.stderr)
if not input_file.suffix == '.csv':
print('The file must be .csv', file=sys.stderr)
exit(1)
try:
with open(input_file, mode="r", encoding="utf-8") as infile:
content = csv.reader(infile)
except IOError:
print('Can not open the file.', file=sys.stderr)
exit(1)
Am I doing something wrong? Files are in the same folder also I double checked, if I am writing the Path right and it looks I am.
CodePudding user response:
argument = sys.argv[:1]
assigns the first element of sys.argv to argument.
BTW it's generally a good idea to print more information in error messages, for example rather than Can not open the file also print the name of the file.
CodePudding user response:
script_name will be the name of the script (as you expected). argument will be a list containing one element and once again that will be the name of your script. As your script probably ends in '.py' the error "The file must be .csv" will occur. I suggest Path(sys.argv[1]) although you need to check that len(sys.argv) > 1