Naman Arora Naman Arora - 1 year ago 41
Python Question

Reading a variable text file from variable directory using python

I am new to python and reckon I'm doing something wrong while trying to access a variable file(text file) from a variable directory. The code that I've written is:

filename = input('Enter filename')
dir = input('Enter directory')

with open('%s/%s.txt' %dir % filename,'r') as myfile:
input ='\n','')

But I'm unable to access the file due to error which says:

TypeError: not enough arguments for format string

Can anyone help me in this?

Answer Source

Your format string is wrong. Try this:

with open('%s/%s.txt' % (dirname, filename),'r') as myfile:
    input ='\n','')

Instead of the above you could also use named parameters using format:

with open('{dirname}/{filename}.txt'.format(dirname=dirname, filename=filename),'r') as myfile:
    input ='\n','')

Also, note that dir is an in-built function so you should not use that as a variable. I changed it to dirname in the example.