Python Forum
how to check if file path finish on .csv
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to check if file path finish on .csv
#1
Hello guys

I have a simple problem finding how can I check if the file path entered by the user does end in for example with .csv
The user enters the file path for a data file (e.g. 'file/myfolder.csv').
If the file path entered by the user does not end in 'csv' then error should be displayed otherwise it should return the path
Reply
#2
Hello guys

I have a simple problem finding how can I check if the file path entered by the user does end in for example with .csv
The user enters the file path for a data file (e.g. 'file/myfolder.csv').
If the file path entered by the user does not end in 'csv' then error should be displayed otherwise it should return the path
Reply
#3
Checking if a file exists, before it is opened, it can still fail.

User enters the right Path and the files exists and has the right file extension. The program continues, but does not open the file directly. If the user or another program deletes the file after the check, but before the open call, you'll get a FileNotFoundError. Other errors are also possible. For example, a PermissionError.

But for a better user experience, it's good to be able to correct the path to the files, if the user makes a mistake. But this is not a replacement for exception handling.

from pathlib import Path


def ask_path(question, allowed_extensions):
    while True:
        file = Path(input(question))
        if file.exists() and file.is_file and file.suffix in allowed_extensions:
            return file

file = ask_path("Please enter the path to your csv-file: ", [".csv"])
# only csv is allowed.
# a Path-Object suffix is a dot + extension
# Path("my_data.csv").suffix -> ".csv" # dot is included
Read more about Pathlib.
It has superpowers.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
What have you tried so far?
Please show code.
Reply
#5
Already sorted thank You but have another problem :(
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Could someone help me finish this ASAP JimmyDricks 7 2,225 Dec-23-2021, 10:30 AM
Last Post: Larz60+
  Need help to finish the hat on the snowman in this Python drawing soowoosamuel 1 3,346 Apr-10-2019, 06:31 AM
Last Post: j.crater
  How to check an array exist in a file using Python fitrisibarani 17 6,636 Feb-27-2019, 04:16 PM
Last Post: ichabod801
  Can Anyone Finish this off FeaRoNz 5 3,949 Mar-25-2017, 10:12 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020