Reputation: 41
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 = myfile.read().replace('\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?
Upvotes: 0
Views: 92
Reputation: 19801
Your format string is wrong. Try this:
with open('%s/%s.txt' % (dirname, filename),'r') as myfile:
input = myfile.read().replace('\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 = myfile.read().replace('\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.
Upvotes: 1