Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Make Script to Manipulate Windows File Paths but running on Linux

I have this script which processes lines containing windows file paths. However the script is running on Linux. Is there a way to change the os library to do Windows file path handling while running on linux?

I was thinking something like:

import os
os.pathsep = '\\'

(which doesn't work since os.pathsep is ; for some reason)

My script:

for line in INPUT.splitlines():
    package_path,step_name = line.strip().split('>')
    file_name = os.path.basename(package_path)
    name = os.path.splitext(file_name)[0]
    print template % (name,file_name,package_path)
like image 929
Greg Avatar asked Sep 08 '10 18:09

Greg


People also ask

How do you pass a path as an argument in Python?

To use it, you just pass a path or filename into a new Path() object using forward slashes and it handles the rest: Notice two things here: You should use forward slashes with pathlib functions. The Path() object will convert forward slashes into the correct kind of slash for the current operating system.

How do I change path to path in Windows Python?

You can use Path function from pathlib library. Use Path(r'P:\python\t\temp. txt') instead it. I specifically mentioned this case in the original question.

What method can be used to create file paths in programs that need to work both in Windows and Linux?

On Windows, paths are written using backslashes (\) as the separator between folder names. OS X and Linux, however, use the forward slash (/) as their path separator. If you want your programs to work on all operating systems, you will have to write your Python scripts to handle both cases.


2 Answers

Look at the ntpath module

On Linux, I did:

>> import ntpath      
>> ntpath.split("c:\windows\i\love\you.txt")
('c:\\windows\\i\\love', 'you.txt')
>> ntpath.splitext("c:\windows\i\love\you.txt")
('c:\\windows\\i\\love\\you', '.txt')
>> ntpath.basename("c:\windows\i\love\you.txt")
'you.txt'
like image 84
Mark Avatar answered Oct 04 '22 01:10

Mark


Try using os.sep = '\\'. os.pathsep is the separator used to separate the search path (PATH environment variable) on the os.

see os module description

like image 31
Rod Avatar answered Oct 04 '22 02:10

Rod