4

我有一个 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'

PS我是python新手,所以也许我犯了一些非常愚蠢的错误谢谢

4

1 回答 1

4

.listdir()方法只为您提供不带路径的文件名,您可能试图在当前目录中打开文件,而不是在path.

您必须使用该os.path.join功能path组合item

for item in added:
    print item
    fullfilename = os.path.join(path, item)
    ad=open(fullfilename,'r')
    print ad.read()
于 2012-08-12T19:56:27.837 回答