Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Python to solve the problem of Windows filename without backslash

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about how to use Python to solve the problem of Windows file names without backslashes, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

In the process of programming, we often encounter a small problem that Microsoft Windows uses backslash characters between folder names, while almost all other computers (operating systems) use forward slashes:

Windows filenames: C:\ some_folder\ some_file.txt Most other operating systems: / some_folder/some_file.txt

This is due to a small accident in the history of computers in the early 1980s. The first version of "MS-DOS" used the forward slash character to specify command line options. When Microsoft added support for folders in "MS-DOS 2.0", the forward slash character was already used, so they used a backslash instead. Thirty-five years later, we are still trapped by this inconsistency.

If you want your Python code to work on both Windows and Mac/Linux, you need to deal with this platform-related problem. Fortunately, Python 3 has a new module called "pathlib" that makes it almost easy for users to work with files.

"pathlib" module link: https://docs.python.org/3/library/pathlib.html

Let's take a quick look at the different ways to deal with filename paths and see how "pathlib" can make your life better!

The wrong solution: build the file path manually

Suppose you have a data folder that contains the files you want to open in your Python program:

It is "wrong" to encode it in Python:

Data_folder = "source_data/text_files/" file_to_open = data_folder + "raw_data.txt" f = open (file_to_open) print (f.read ())

Note that since I am using the Mac system, I hard-coded the path using a forward slash in the "Unix" style. This will also make Windows users angry.

Technically, this code still works on Windows because Python has a "hack" technique: when you call the "open ()" function on Windows, it recognizes these two slashes. But even so, you shouldn't rely on it. If you use the wrong type of slash on the wrong operating system (especially if they interact with external programs or code bases), not all Python libraries will work.

Python's support for mixed slash types is a "hacker" technology for Windows only, and it doesn't work the other way around. In a Mac system environment, using a backslash in your code can lead to complete failure:

Data_folder = "source_data\\ text_files\" file_to_open = data_folder + "raw_data.txt" f = open (file_to_open) print (f.read ()) # On a Mac, this code will throw an exception: # FileNotFoundError: [Errno 2] No such file or directory: 'source_data\\ text_files\\ raw_data.txt'

For all these and other reasons, writing code in hard-coded path strings is a practice that other programmers will dislike. Generally speaking, you should try to avoid doing so.

Previous solution: Python's "os.path" module

Python's "os.path" module has many tools to deal with such operating system-specific file system problems.

You can use "os.path.join ()" to build a path string with the correct type of slash for the current operating system:

Import os.path data_folder = os.path.join ("source_data", "text_files") file_to_open = os.path.join (data_folder, "raw_data.txt") f = open (file_to_open) print (f.read ())

This code works perfectly on both "Windows" and "Mac" systems. The problem is that it is troublesome to use. Writing out "os.path.join ()" and passing each part of the path to the function as a separate string is lengthy and unintuitive.

Because most of the functions in the "os.path" module are annoying to use, developers often "forget" to use them, even if they know it's better. This has led to the emergence of a lot of cross-platform Bug, but also caused the anger of users.

A better solution: "pathlib" of Python 3!

To deal with files and paths, Python 3.4introduces a new standard library called "pathlib", and it works very well!

To use the library, you simply use a forward slash to pass a path or file name to a new "Path ()" object, and it will handle the rest of the operation:

From pathlib import Path data_folder = Path ("source_data/text_files/") file_to_open = data_folder / "raw_data.txt" f = open (file_to_open) print (f.read ())

Here, there are two points to note:

You should use a forward slash when using the "pathlib" function. The "Path ()" function will convert the forward slash to the correct slash adapted to the current operating system environment. Yes!

If you want to add to the path, you can use the "/" operator directly in your code. You don't have to type "os.path.join (a, b)" over and over again.

If that's all "pathlib" has done, it's already a good addition to Python. But it can do more!

For example, we can read the contents of a text file without opening and closing the file:

From pathlib import Path data_folder = Path ("source_data/text_files/") file_to_open = data_folder / "raw_data.txt" print (file_to_open.read_text ())

Professional tip: the previous example has Bug, because the open file has never been closed. This syntax here completely avoids the Bug.

In fact, "pathlib" makes most standard file operations fast and easy:

From pathlib import Path filename = Path ("source_data/text_files/raw_data.txt") print (filename.name) # prints "raw_data.txt" print (filename.suffix) # prints "txt" print (filename.stem) # prints "raw_data" if not filename.exists (): print ("Oops, file doesn't exist!") Else: print ("Yay, the file exists!")

You can even use "pathlib" to explicitly convert a "Unix" path to a "Windows" format:

From pathlib import Path, PureWindowsPath filename = Path ("source_data/text_files/raw_data.txt") # Convert path to Windows format path_on_windows = PureWindowsPath (filename) print (path_on_windows) # prints "source_data\ text_files\ raw_data.txt"

If you really want to safely use backslashes in your code, you can declare your path in "Windows" format, and "pathlib" can convert it to work in the current operating system:

From pathlib import Path, PureWindowsPath # I've explicitly declared my path as being in Windows format, so I can use forward slashes in it. Filename = PureWindowsPath ("source_data\\ text_files\\ raw_data.txt") # Convert path to the right format for the current operating system correct_path = Path (filename) print (correct_path) # prints "source_data/text_files/raw_data.txt" on Mac and Linux # prints "source_data\ text_files\ raw_data.txt" on Windows

If you want to make the code more "advanced", you can even use "pathlib" to do things such as parsing relative paths, parsing network sharing paths, and generating "file:// urls". In the following example, we will use only two lines of code to open a local folder in your web browser:

From pathlib import Path import webbrowser filename = Path ("source_data/text_files/raw_data.txt") webbrowser.open (filename.absolute () .as_uri ())

This is just one of the benefits of "pathlib". It is a good substitute for many different file-related functions that used to be scattered in different Python modules.

After reading the above, do you have any further understanding of how to use Python to solve the problem of Windows filenames without backslashes? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report