新代码:
如果文件不在文件夹中。然后我不想制作新的目录。
import os
try:
filename = "test123.pdf"
folder = "someFolder"
os.mkdir (folder)
os.rename(filename,"someFolder\\test123.pdf")
except:
print "File not found"
答案 0 :(得分:0)
如果你想只在第4行成功的情况下运行第3行,那么最好将要打印的每个字符串组合成一个数组,然后在所有行成功后打印结果:
print "Print ME"
strings = []
try:
strings.append("1)Only print if try go through")
strings.append(1/0) # this line will fail because of divide by zero
strings.append("2)Only print if try go through")
print str.join("\n", strings) # this would only print if above statements succeeded
except:
print "Fail"
答案 1 :(得分:0)
如果您希望第3行仅在第4行成功时运行,则需要使用第4行切换第3行。
答案 2 :(得分:0)
虽然流行的Python风格是"请求宽恕而不是寻求许可",这似乎是一个很好的地方,而不是采用"在你跳跃之前看看#34;。在采取任何行动之前,实际检查文件是否存在。
import os
filename = "test123.pdf"
folder = "someFolder"
if os.path.isfile(filename):
os.mkdir (folder)
os.rename(filename,"someFolder\\test123.pdf")
else:
print "file not found"
答案 3 :(得分:0)
由于问题现在与原始形式完全不同,我正在添加一个新答案。
根据条件执行语句意味着您应该使用if
语句。
import os
try:
filename = "test123.pdf"
folder = "someFolder"
if filename not in os.listdir(folder): # this line is the key
os.mkdir (folder)
os.rename(filename,"someFolder\\test123.pdf")
except:
print "File not found"
答案 4 :(得分:0)
在您的情况下,您可以在采取行动之前进行测试:
import os
try:
filename = "test123.pdf"
if not os.path.isfile(filename):
raise OSError("File not found")
folder = "someFolder"
os.mkdir (folder)
os.rename(filename,"someFolder\\test123.pdf")
except:
print "File not found"
或者,如果您想处理其他问题,例如无权移动文件,请稍后解压缩:
import os
try:
filename = "test123.pdf"
folder = "someFolder"
os.mkdir (folder)
os.rename(filename,"someFolder\\test123.pdf")
except:
if os.path.isdir(folder):
os.rmdir(folder)
print "File not found"