我有一个 Python 脚本,用于查找文件文件夹(添加/删除)中的任何更改。 我正在寻找添加的任何新文件并想打开它们并从中读取一些数据。
代码是
# Utility to check for any new jobs
import os
import win32file
import win32event
import win32con
import string
path= r"C:\Users\dZONE\Desktop\py"
change_handle = win32file.FindFirstChangeNotification (path,0,win32con.FILE_NOTIFY_CHANGE_FILE_NAME)
try:
old_path_contents = dict ([(f, None) for f in os.listdir (path)])
while 1:
result = win32event.WaitForSingleObject (change_handle, 500)
if result == win32con.WAIT_OBJECT_0:
new_path_contents = dict ([(f, None) for f in os.listdir (path)])
added = [f for f in new_path_contents if not f in old_path_contents]
#deleted = [f for f in old_path_contents if not f in new_path_contents]
if added: print "Added: ", ", ".join (added)
#if deleted: print "Deleted: ", ", ".join (deleted)
# My open
print "Len" , len(added)
for item in added:
print item
ad=open(item,'r')
print ad.read()
old_path_contents = new_path_contents
win32file.FindNextChangeNotification (change_handle)
finally:
win32file.FindCloseChangeNotification (change_handle)
当我尝试打开该文件时,出现 IO 错误 13。尽管我拥有文件夹和文件的权限。我编写了另一个测试代码并尝试打开同一个文件,直接将文件名提供给 open(),它确实有效。
如果有人能指出我正在做的错误,我们将不胜感激。
编辑:错误信息
Traceback (most recent call last):
File "C:\Users\dZONE\Desktop\py\util.py", line 50, in <module>
ad=open(item,'r')
IOError: [Errno 13] Permission denied: 'ad.sjs_hdr'
P.S 我是 python 的新手所以也许我犯了一些非常愚蠢的错误 谢谢
最佳答案
.listdir()
方法只给你没有路径的文件名,你可能试图在 当前 目录中打开一个文件,而不是在由 path
命名的目录中.
您必须使用 os.path.join
function放path
和 item
一起:
for item in added:
print item
fullfilename = os.path.join(path, item)
ad=open(fullfilename,'r')
print ad.read()
关于python - IOError : [Errno 13] Permission denied, 打开文件时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11924981/