Billjk
Billjk

Reputation: 10686

File Naming, Python

What I am trying to do in Python, is make a program where you can write to a file directly from the command line. I have all the code to do this, but the only relevant code is below.

aw = input("Do you want to append your text file, or rewrite the whole thing? (append/write) ")
if aw == 'append':
    textin = input("In the line below, write the text you want to put into your text document!\n\n")
    outfile = open('mytext.txt', 'a')
    outfile.write(textin)

What I am trying to do is make it so people can choose the filename, but when I do an input function, name = input("Choose your filename, don't include an extension: ") and change line 4 into outfile = open(name, 'txt', 'a'), I get a syntax error!

Upvotes: 2

Views: 409

Answers (1)

Ben Russell
Ben Russell

Reputation: 1423

Try this instead: outfile = open(name + '.txt', 'a')

Python cannot concatenate strings like that and so was treating open(name, 'txt', 'a') as a function call with three arguments. Unfortunately the open function only takes two.

Edit: If this is Python 2.x code, then you are also using the input function incorrectly. According to the documentation the input function requires the user to type valid python code, you are looking for the raw_input function.

If this is Python 3.x code, then the correct function is input and my apologies.

Upvotes: 2

Related Questions