Converting Windows Path to Linux

Onur Ozbek :

I created a CSV file (driving_log.csv) for the filepath of each image that my simulator created but I was using my brother's Windows computer when I did that so now the file path looks like this for each image (and there is almost 14000 of them). I get an error when invoking it from my file.py, which is in the same directory as the CSV file.

C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\center_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\left_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06

I'm using Arch Linux. I want to iterate through each line and change it to this:

/home/onur/Documents/behavioral-cloning-CARLA/IMG/center_2020_02_08_14_16_38_988.jpg,left_2020_02_08_14_16_38_988.jpg,right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06

As you can see, I need everything that comes after \IMG\.

What is the best way to go about this? Should I just slice each string at IMG\ and take what's after it or use regex?

I've tried this for this specific line to see if it works but it doesn't:

string = r"C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\center_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\left_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06 "

new_string = string.replace(r"'C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\'", r"'/home/onur/Documents/behavioral-cloning-CARLA/IMG/'", 3)

print(new_string)

This is the output:

C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\center_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\left_2020_02_08_14_16_38_988.jpg,C:\Users\a-ozb\Desktop\onur\behavirol-cloning-carla\IMG\right_2020_02_08_14_16_38_988.jpg,0,0,0,7.918889E-06 
Selcuk :

If you are running your code on a *nix machine, you can use the PureWindowsPath class:

>>> from pathlib import PureWindowsPath, PurePosixPath
>>> path = PureWindowsPath('C:\\Users\\foo\\bar')

>>> path.parts
('c:\\', 'Users', 'foo', 'bar')

>>> PurePosixPath('/usr', *path.parts[2:])
PurePosixPath('/usr/foo/bar')

You can apply the string replace method to every line in a text file as follows:

with open("input.csv", "r") as f_in:
    with open("output.csv", "w") as f_out:
        for line in f_in:
            new_line = line.replace(...)  # magic goes here
            f_out.write("{}\n".format(new_line))

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=6617&siteId=1