SoFunction
Updated on 2024-11-19

Three ways for python to read a file path correctly

Python's way of reading a file path correctly

Problem demand

When you use a program to read file data in daily life, it often displays some error messages such as file path does not exist.

Cause of the problem

This type of problem, in python, is mainly due to the fact that the"\" (backslash) Cause.

This is because on Windows, a backslash (\) is used as a file path separator, but in python, a backslash (\) is identified as aescape characterCause.

The resulting program reports an error.

method settle an issue

The following three solutions are commonly used to address the above problems.

Take the file path in Windows: "E:\CloudMusic\MV\" as an example.

Method 1 Replaces single backslashes in paths with double backslashes.

As shown below:

“E:\CloudMusic\MV\”

Method 2 Adding r in front of the path keeps the character in its original meaning.

As shown below:

r"E:\CloudMusic\MV\"

Method 3 Replace backslashes with forward slashes (/).

As shown below:

“E:/CloudMusic/MV/”

Just choose to adjust it according to your own habits.

Attention:

Different systems or languages, some operations or characters will inevitably have some special meaning, pay attention to summarize, you can avoid many small errors.

Reasons why python fails to read file paths

Today I used tensorflow to read a csv file, and it kept failing to read it, and then I realized it was because of the path to the file name

Example:

DATA_FILE = ['F:\vscode\']

The reason for the error at this point is that the system interprets '\' as an escaped string, and even if it's placed under the current path, writing just the filename will still fail.

It is not clear why the vscode software does not recognize the current path.

Anyway just use the correct absolute path.

To avoid escaped characters that cause errors in parsing the file address, we can use a double slash, or a reverse slash.

DATA_FILE = ['F:\\vscode\\']
DATA_FILE = ['F:/vscode/']

summarize

The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.