Home > other >  Check if multiple files are present in particular location if yes then proceed with the code else re
Check if multiple files are present in particular location if yes then proceed with the code else re

Time:06-23

Consider i have 5 files in 5 different location. Example = fileA in XYZ location fileB in ZXC location fileC in XBN location so on

I want to check if these files are actually saved in that location if they are not re run the code above that saves the file.

Ex:

if:
 fileA, fileB so on are present in their particular location  the proceed with code further 
else:
re run the file saving code above

How do i do this in python i am not able to figure out.

CodePudding user response:

You can store all your file with their locations in a list and then iterate all locations for existance then you can decide further what to do a python example is following

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 status of all files if any of the file not exists, else will be called
if(all(status)):
    print('All files are present')
else:
    print('May be all or any one of them is not actually exist')

CodePudding user response:

I'm not a python dev, and I just wanted try to contribute to the community. The first answer is way better than mine, but I'd like to share my solution for that question.

You could use sys to pass the files' names, inside a try block to handle when the files are not found. If you run the script from a location while the files are at another location, it would be needed to provide their path. 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")

The exception part would then "save" the files, by creating new ones, writing whatever content you desire.

  • Related