geek_xed
geek_xed

Reputation: 175

How to specify filename in os.path.join in python

I have

fruits = [ apple, pineapple, oranges, mango, banana ]
size = [small, medium, large] 

I am trying to create paths for all combinations of fruits with sizes as below:

for fruit, size in itertools.product(fruits, sizes):
    main-directory = sys.argv[1]
    sizefilepath = os.path.join(maindirectory, fruit, "business", fruit_size.dot)

    try:
       sizefile = open(sizefilepath, "r")
    except:
       print("could not open" +sizefilepath)
    sizefile.close()

     estimatefilepath = os.path.join(maindirectory, "get", "estimate", "of", fruit_size.txt)  
     try: 
        estimatefile = open(estimatefilepath)
     except:
        print("could not open"+estimatefilepath)
     estimatefilepath.close() 

When I execute the code it gives an error that fruit_size is not defined. and when I define

fruit_size = [different comibinations like apple_small etc.]

it gives an error that there is no attribute as .txt for string.

How to tackle the error? Also My remaining code makes use of sizefile and estimatefile. How can I sequence the execution? like for all fruit I want to execute it one by one. Currently if I try, I get value error : I/O operation on closed file.

Upvotes: 0

Views: 1495

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90899

If the sizefile filename you want is something like - <fruit>_<size>.dot , example - apple_small.dot and the second file name needs to be <fruit>_<size>.txt then what you are using is wrong, python will assume fruit_size to be an object with .dot to be a variable inside that object , which is not the case, you want to use string concatenation here.

Example -

for fruit, size in itertools.product(fruits, sizes):
    maindirectory = sys.argv[1]
    sizefilepath = os.path.join(maindirectory, fruit, "business", fruit + "_" + size + ".dot")

    try:
       sizefile = open(sizefilepath, "r")
    except:
       print("could not open" +sizefilepath)
    sizefile.close()

     estimatefilepath = os.path.join(main-directory, "get", "estimate", "of", fruit + "_" + size + ".txt")  
     try: 
        estimatefile = open(estimatefilepath)
     except:
        print("could not open"+estimatefilepath)
     estimatefilepath.close() 

Upvotes: 1

Related Questions