shutil.move 问题 - 多余的 \
我有一个日志文件,在这个日志里,有些文件出现了错误。所以当一个文件出错时,我想读取它的名字(包括路径),然后把它移动到另一个文件夹。
我可以正常读取输入文件,比如说其中一个文件是:C:\test\test1,我可以找到这个文件,我只想把它移动。但是,当我使用shutil.move(filename, another_directory)时,尽管打印出来的filename显示的是c:\test\test1,shutil却在每个斜杠前面多加了一个反斜杠……也就是说,它试图移动的是C:\\test\\test1。[shutil.move错误地在每个已有的反斜杠前面加了一个反斜杠]
我该怎么解决这个问题呢?谢谢!
import shutil
f=open("test_logs")
o=open("output_logs","w")
e=open("error_logs",'w')
another_directory= "C:/test"
for line in f:
if line.lstrip().startswith("C:"):
filename = line
#print line
#look for errors in the next line onwards.
if line.startswith("error"):
e.write(filename + "\n")
print filename
shutil.move(filename,another_directory)
f.close()
o.close()
这是我收到的错误 - IOError: [Errno 2] 没有这样的文件或目录: 'C:\\test\\test1'(实际上文件是C:\test\test1),而打印出来的filename显示的是c:\test\test1
2 个回答
这里有几个问题。
从你编辑后的错误信息来看,我发现你在尝试把 C:/test/test1 移动到 C:/test/test1... 如果我没记错的话,这在 Windows 系统上总是会失败。建议你换一个目标文件夹来测试一下。
another_directory = "C:\test"
目标路径应该是 "C:/test",或者使用 os.path.join 等方法。
for line in f:
if line.lstrip().startswith("C:"):
filename = line
#print line
if line.startswith("error"):
e.write(filename + "\n")
print filename
shutil.move(filename,another_directory)
这两个条件不可能同时为真,所以你应该是从之前的行中提取文件名,然后在后面的行中检查是否有 "error"。不过,line.lstrip() 这个方法并不会改变原来的 line,它只是返回一个新的值。当你把保存的值(在 filename 里)写入错误日志时,会出现两个换行符——一个是在 filename 里。然后当你试图移动那个文件时,它并不存在,因为 "filename" 里仍然包含了换行符和你用 lstrip() 去掉的空格。
another_directory= "C:/test"
filename = None
for line in f:
if line.lstrip().startswith("C:"):
filename = line.strip() # Remove both leading and trailing WS.
print "File:", filename, "(exists: %s)" % os.path.exists(filename)
elif line.startswith("error"):
assert filename is not None # Do a sanity check as required.
e.write(filename + "\n")
print "Moving %s..." % filename
shutil.move(filename, another_directory)
根据关于 shutil.move
的文档:
如果目标位置在当前的文件系统上,那就直接用重命名(rename)就可以了。否则,就先用 copy2() 把源文件(src)复制到目标位置(dst),然后再删除源文件(src)。
... 在这种情况下,你应该使用 os.rename
,因为这两个文件确实在同一个文件系统上。不要这样做:
shutil.move(filename,another_directory)
要这样做:
directory, name = os.path.split(filename)
os.rename(filename, os.path.join('c:', 'test', name))
从你收到的错误信息来看,我们可以推测 shutil.move
失败的原因是它期望目标文件已经存在,但实际上并没有。