开发者

Python delete file, invalid path

开发者 https://www.devze.com 2023-04-02 22:30 出处:网络
I want to delete a file located on my desktop: os.remove(\'C:/Benutzer/Me/Desktop/sync.txt\') But I get

I want to delete a file located on my desktop:

os.remove('C:/Benutzer/Me/Desktop/sync.txt')

But I get

[Error 3] System cannot find the path

However the file does exist in the given location. I can copy the path and paste into explorer. This will open the file.

W开发者_开发知识库here is the problem?


I suppose you are on Vista or 7? Then be aware of the UI to do quite a lot of localization.

Probably the path is really C:\Users\..., with the localization to Benutzer happening in the UI.


Try using backslashes instead of slashes, i.e. 'C:\Benutzer\Me\Desktop\sync.txt' (dos/windows style paths). To avoid the backslashes from being treated as escaping character use a raw string:

os.remove(r'C:\Benutzer\Me\Desktop\sync.txt')


Are you sure the directory path is correct, if slashes causing problem (dont have to be) try this:

import os
filePath = 'C:' + os.path.sep + 'Benutzer' + os.path.sep + 'Me' + os.path.sep + 'Desktop' + os.path.sep + 'sync.txt'
os.remove(filePath)

the advantage of using os.path.sep here is that now you dont have to worry whether you are on linux or windows or whatever...


This looks like the correct answer. I googled and found this: link

Folder name (and path) in Windows XP Documents and Settings (C:\Documents and Settings)

In Vista and 7 it is moved to c:\Users

0

精彩评论

暂无评论...
验证码 换一张
取 消