Search code examples
pythonfileraw-input

Python raw_input for file writing


I have the following code:

print "We're going to write to a file you'll be prompted for"
targetfile = raw_input('Enter a filename: ')
targetfilefound = open('targetfile' , 'w')
print "What do we write in this file?"
targetfilefound.write("hello this is working!")
targetfilefound.close()

The script I'm creating should be able to write to a file that the user defines via raw_input. The above could be faulty at core, open to suggestions.


Solution

  • Judging by the stuff the script is printing you probably want the user to input what should be printed to the file so:

    print "We're going to write to a file you'll be prompted for"
    targetfile = raw_input('Enter a filename: ')
    targetfilefound = open(targetfile , 'w')
    print "What do we write in this file?"
    targetfilefound.write(raw_input())
    targetfilefound.close()
    

    Note: This method will create the new file if it does not exist. If you want to check whether the file exists you can use the os module, something like this:

    import os
    
    print "We're going to write to a file you'll be prompted for"
    targetfile = raw_input('Enter a filename: ')
    if os.path.isfile(targetfile) == True:
        targetfilefound = open(targetfile , 'w')
        print "What do we write in this file?"
        targetfilefound.write(raw_input())
        targetfilefound.close()
    else:
        print "File does not exist, do you want to create it? (Y/n)"
        action = raw_input('> ')
        if action == 'Y' or action == 'y':
            targetfilefound = open(targetfile , 'w')
            print "What do we write in this file?"
            targetfilefound.write(raw_input())
            targetfilefound.close()
        else:
            print "No action taken"