考慮我在 5 個不同的位置有 5 個檔案。示例 = XYZ 位置中的檔案 A 在 ZXC 位置中的檔案 B 在 XBN 位置中的檔案 C 依此類推
如果這些檔案沒有重新運行上面保存檔案的代碼,我想檢查這些檔案是否實際保存在該位置。
前任:
if:
fileA, fileB so on are present in their particular location the proceed with code further
else:
re run the file saving code above
我如何在python中做到這一點我無法弄清楚。
uj5u.com熱心網友回復:
您可以將所有檔案及其位置存盤在串列中,然后迭代所有位置以使其存在,然后您可以進一步決定要做什么。
一個 Python 示例:
from os.path import exists
# all files to check in different locations
locations = [
'/some/location/xyz/fileA',
'/other/location/fileB',
'/yet/another/location/fileC',
]
# iterate to check each file existance
status = [exists(location) for location in locations]
# check the status of all files
# if any of the files doesn't exist, else will be called
if(all(status)):
print('All files are present.')
else:
print('Any or all files do not exist.')
uj5u.com熱心網友回復:
我不是 python 開發人員,我只是想嘗試為社區做出貢獻。第一個答案比我的要好得多,但我想分享我對這個問題的解決方案。
您可以使用在未找到檔案時在塊sys
內傳遞檔案的名稱。try
如果您在檔案位于另一個位置時從一個位置運行腳本,則需要提供它們的路徑。
check.py ../test1.txt ../test2.txt ../test3.txt
#!/usr/bin/python3
import os.path
import sys
try:
fpath = sys.argv[1]
fpath = sys.argv[2]
fpath = sys.argv[3]
if (os.path.isfile(fpath)) != "":
print("Exists on system")
else:
pass
except IndexError:
for i in range(3):
file1 = "test1.txt"
file2 = "test2.txt"
file3 = "test3.txt"
sys.stdout = open(file1, "w")
print("Saving content to files")
sys.stdout = open(file2, "w")
print("Saving content to files")
sys.stdout = open(file3, "w")
print("Saving content to files")
然后,該exception
部件將通過創建新檔案、撰寫您想要的任何內容來“保存”檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495164.html
標籤:Python for循环 if 语句 while循环 jupyter-笔记本