0

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?

1
  • 1
    Where did you learn that syntax from? Commented May 8, 2016 at 7:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I get the following error: OSError: [Errno 22] Invalid argument: '<built-in function dir>/asthma.txt'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.