2013-08-22 2 views
0

파일 이름에 비 ASCII 문자가 포함되어 있으면 파일의 속성을 읽는 데 파이썬을 사용하는 데 문제가 있습니다. 예를 들어 파일의이름에 특수 (비 ASCII) 문자가 포함 된 파일의 속성 가져 오기

하나의 이름은 :이 프로그램을 실행할 때

0-Channel-https∺∯∯services.apps.microsoft.com∯browse∯6.2.9200-1∯615∯Channel.dat

: 나는 그것의 원인이 가정

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: '0-Channel-https???services.apps.microsoft.com?browse?6.2.9200-1?615?Channel.dat' 

:

list2 = os.listdir('C:\\Users\\James\\AppData\\Local\\Microsoft\\Windows Store\\Cache Medium IL\\0\\') 
for data in list2: 
    print os.path.getmtime(data) + '\n' 

내가 오류 ASCI 만있는 다른 파일 이름과 코드가 잘 작동하기 때문에 특수 문자가 필요합니다. 나는 chars.

누구나 이와 같은 파일의 파일 시스템 속성을 쿼리하는 방법을 알고 있습니까? 당신이 창에있는 것처럼 나는 그것을 테스트 할 수 없습니다 창을 가지고 있지 않기 때문에

답변

1

이것이 파이썬 2.x 인 경우 인코딩 문제입니다. os.listdir에 유니 코드 문자열을 u'C:\\my\\pathname'과 같이 전달하면 유니 코드 문자열이 반환되고 올바르게 인코딩되지 않은 ASCII 문자가 있어야합니다. 문서의 Unicode Filenames을 참조하십시오.

해당 문서를 인용 :

os.listdir(), which returns filenames, raises an issue: should it return the Unicode version of filenames, or should it return 8-bit strings containing the encoded versions? os.listdir() will do both, depending on whether you provided the directory path as an 8-bit string or a Unicode string. If you pass a Unicode string as the path, filenames will be decoded using the filesystem’s encoding and a list of Unicode strings will be returned, while passing an 8-bit path will return the 8-bit versions of the filenames. For example, assuming the default filesystem encoding is UTF-8, running the following program:

이 코드가 작동합니다 ...

directory_name = u'C:\\Users\\James\\AppData\\Local\\Microsoft\\Windows Store\\Cache Medium IL\\0\\' 
list2 = os.listdir(directory_name) 
for data in list2: 
    print data, os.path.getmtime(os.path.join(directory_name, data)) 
+0

도움 주셔서 감사합니다. 문제가 해결 된 것 같습니다. 이제 파일 이름을 인쇄하면 특수 문자가 포함되지만 물음표로 바꾸기 전에 특수 문자가 포함됩니다. 대신 WindowsError : [오류 2] 지정한 파일을 찾을 수 없습니다. 비록 그것은 listdir 함수로부터 모아 놓았습니다. 확실하게 나는 그것을 결국 이해하지 못한다. 다시 도움을 주셔서 감사합니다 – Xtrato

+0

listdir은 상대 경로 이름을 제공합니다. 또한 os.path.join()이 필요합니다 - 게시물을 업데이트합니다. 내 컴퓨터에서 파일 이름을 찾았지만 제대로 작동 했으므로 가까이 있어야합니다. – tdelaney

0

당신은 ntpath 모듈 대신을 os.path

from ntpath import getmtime 

으로 시도해야합니다. 모든 os는 다른 경로 규칙을 가지고 있으므로 파이썬은 가장 일반적인 운영 시스템을위한 특정 모듈을 제공합니다.

+1

아니,을 os.path는 플랫폼 특정 버전으로 단지의 별칭입니다. Windows에서 os.path는 ntpath입니다. – tdelaney

+0

고마워. 말된다. – moliware