0

I'm not sure how to word the question, and I'm not finding anything in searches.

I have a variable, and want to pass it into f.open() as the name of the file to open. The goal is to type a file name into foo, then it clears the files.

foo = str(raw_input('enter a filename '))
bar = foo   
f = open('foo', 'w')
f.write("")
f.close()

I've tried using open(foo, 'w') and replacing it with 'bar', but neither seems to work. Any suggestions?

6
  • What does it mean "doesn't seems to work"? What exactly happens? It should work Commented Feb 13, 2017 at 17:40
  • Also, str is unnecessary when you get raw_input Commented Feb 13, 2017 at 17:41
  • Replace 'foo' with foo Commented Feb 13, 2017 at 17:42
  • It would run, but instead of clearing the file it would make a new file named "foo". Removing the quotes got it to work Commented Feb 13, 2017 at 17:44
  • The line f.write("") can be removed. You can even write open(foo, 'w').close(). Commented Feb 13, 2017 at 17:47

2 Answers 2

2

Remove the '' from 'foo':

f = open('foo', 'w')

Like this:

f = open(foo, 'w')

'foo' is a literal string and foo is a variable name that holds the file name the user entered.

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

Comments

1

f = open(bar, 'w')

Just pass the variable name (without quotes of course).

Additionally, you don't need the line bar = foo. You are already storing the filename as foo with your first line.

So... if you remove bar = foo it would be f = open(foo, 'w')

1 Comment

Don't know how i missed that. Must have been doing it wrong when i tried earlier. Thanks :)

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.