我认为这是一项简单的任务。我尝试了很多事但没有成功。
我想在网络目录中使用文件A,当我离线时,我想在我的ssd上使用文件B.
x$even_deaths <- ave(x$deaths, x$year, x$actor, FUN = function(x) x/length(x))
x
# year actor deaths even_deaths
#1 1992 Taliban 300 100.0
#2 1992 Taliban 300 100.0
#3 1992 Taliban 300 100.0
#4 1994 Taliban 100 50.0
#5 1994 Taliban 100 50.0
#6 1995 Taliban 250 250.0
#7 1992 Afghanistan 25 12.5
#8 1992 Afghanistan 25 12.5
#9 1993 Afghanistan 60 60.0
它不适用于这段代码。 当我重命名file_A进行测试时,将不会使用file_B。
更新
我发现了(非常愚蠢)的错误。这是两个目录之一的拼写错误。
答案 0 :(得分:1)
使用os.path.exists并考虑使用os.path.join来构建路径。
@get_transaction_info = 1
答案 1 :(得分:1)
import pathlib
file_PATH = pathlib.Path('y:/file_A.txt')
if file_PATH.is_file():
file_to_use = "y:/file_A.txt"
else:
file_to_use = "d:/file_B.txt"
编辑:由于对Python 3.4的评论
您可以使用Python os.path.exists进行此操作:
>>> import os.path
>>> file_path = 'c:/file_false.txt'
>>> os.path.exists(file_path)
False
>>> file_path = 'c:/file_real.txt'
os.path.exists(file_path)
True
所以
import os.path
file_PATH = 'y:/file_A.txt'
if os.path.exists(file_path):
file_to_use = "y:/file_A.txt"
else:
file_to_use = "d:/file_B.txt"
答案 2 :(得分:0)
我建议您检查文件是否存在。
在python 3.4中:pathlib模块提供了面向对象的方法 - :
from pathlib import Path
if Path(r"/path/to/file_A.txt").is_file():
file_to_use = "y:/file_A.txt"
elif Path(r"/path/to/file_B.txt").is_file():
file_to_use = "d:/file_B.txt"
else:
# Do something if both files don't exist