Thay thế dấu gạch chéo ngược bằng dấu gạch chéo về phía trước

Richard D. Moores rdmoores tại gmail. com
CN 31 tháng 7 11. 35. 00 CEST 2011
On Sat, Jul 30, 2011 at 23:32, Sandip Bhattacharya
<sandipb at foss-community.com> wrote:
>
> On Sat, Jul 30, 2011 at 10:28:11PM -0700, Richard D. Moores wrote:
> > File "c:\P32Working\untitled-5.py", line 2
> >    return path.replace('\', '/')
> >                                ^
> > SyntaxError: EOL while scanning string literal
> > Process terminated with an exit code of 1
>
> The first backslash up there is escaping the ending quote. This is  what
> you want:
>    return path.replace('\\', '/')
>
> Generally, converting slashes manually should be kept at a minimum. You
> should be using library functions as much as possible. The experts here
> can correct me here, but this is a roundabout way I would be doing this:
>
>    # I use a linux machine. Using this to work with Windows paths
>    # Use os.path if you are on windows
>    import ntpath
>
>    # Use raw strings so that backslash doesnt matter
>    path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>
>    #take out drive first because ntpath.split end sentinel is predictable that way
>    drive,rest = ntpath.splitdrive(path)
>
>    # This will store the path components
>    comps = []
>    comps.append(drive)
>
>    while rest != '\\':
>        parts = ntpath.split(rest)
>        comps.insert(1,parts[1])
>        rest = parts[0]
>
>
>    print '/'.join(comps)
>
> I am not happy with the loop to collect the components. But I couldn't
> find a single path function which splits a path into all the components
> in one go.

Terrific! I now have my function, thanks to Sandip:

def fwd2bk_path_slashes(path):
    import os.path

    # Use raw strings so that backslash doesn't matter
    #path=r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'

    #take out drive first because os.path.split end sentinel is
predictable that way
    drive, rest = os.path.splitdrive(path)

    # This will store the path components
    comps = []
    comps.append(drive)

    while rest != '\\':
        parts = os.path.split(rest)
        comps.insert(1, parts[1])
        rest = parts[0]

    return ('/'.join(comps))


I've put it in my mycomp.py module, my collection of useful functions.
>>> from mycalc import fwd2bk_path_slashes
>>> path = r'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
>>> fwd3bk_path_slashes(path)
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'


BTW I had figured out that I could solve my problem if I either
manually doubled all the backslashes in the path or manually changed
each backslash to a forward slash, but that wouldn't solve my problem
-- I wanted a function that would convert paths such as

'C:\Users\Dick\Desktop\Documents\Notes\College Notes.rtf'
to paths such as
'C:/Users/Dick/Desktop/Documents/Notes/College Notes.rtf'

I can live with having to put the path in single quotes and then
precede this with an  r  .

===============Stop reading here; what follows is OT====================

I'll explain why I wanted the function for those few who might be curious:

I have a bunch of RTF files which are used to collect one sort of
information or another. Comcast Voicemail Notes.rtf, Diary.rtf, Python
Notes.rtf, IPython Notes.rtf, Vista Notes.rtf, Agent Ransack Tips.rtf,
etc.

I also use ActiveWords (http://www.activewords.com/). I've been using
it for years, and now have over 1600 "active words" that do all sorts
of things for me: access websites (with my default browser), call
programs, open folders, execute Python programs, etc. And of course,
open files such as those RTF files. One of those RTFs is
ActiveWords,rtf (which I open using the activeword 'aw'. 'nyt' gets me
to the New York Times; 'at' (for 'add times') executes/calls my Python
script for adding times (such as track times on a CD), 'prec' (for
'precision') enters an often used bit of code,
'decimal.getcontext().prec ='.

Now of course I can remember only the activewords that I frequently
use. To retrieve the others of the 1600+, I have them all listed, one
per line in ActiveWords.rtf, and have a Python script that essentially
greps them for the one I want. Each line has the activeword, a short
description of what it does, and the path if the activeword opens a
folder or a file. For each path, I copy it from Windows Explorer
(using Shift when I right-click on the file or folder, then select
'Copy as path' from the context menu that opens. But if I paste this
into its line in ActiveWords.rtf, my grepping script makes a mess of
it. Therefore my need for a function to first convert those
backslashes to forward slashes.

Dick


Thông tin thêm về danh sách gửi thư Tutor

Tôi có nên sử dụng dấu gạch chéo lên hoặc dấu gạch chéo ngược trong Python không?

Các ngôn ngữ lập trình, chẳng hạn như Python, coi dấu gạch chéo ngược (\) là ký tự thoát. Chẳng hạn, \n đại diện cho một nguồn cấp dữ liệu và \t đại diện cho một tab. Khi chỉ định một đường dẫn, có thể sử dụng dấu gạch chéo lên (/) thay cho dấu gạch chéo ngược . Có thể sử dụng hai dấu gạch chéo ngược thay vì một để tránh lỗi cú pháp.

Dấu gạch chéo về phía trước có phải là một ký tự đặc biệt trong Python không?

Tài liệu mô tả cú pháp của biểu thức chính quy trong Python. Như bạn có thể thấy, dấu gạch chéo lên không có chức năng đặc biệt .