Hi all. I am very new at python and so i am having trouble with the simplest things, and i dont understand why this:
newfile = raw_input('what do you want to name your new file?')
text_file = open (newfile, "w")
isn't working. Can somebody explain it? Thankyou

Member Avatar for masterofpuppets

well, you need to put the .txt extension at the end of the newFile input to get a text file

newfile = raw_input( 'What do you want to name your new file? ')
text_file = open ( newfile, "w" )
line = raw_input( "Enter a line to write to the %s file >> " % ( newfile ) )
text_file.write( line )
text_file.close()

print "\nContents of the new file:",
text_file = open( newfile, "r" )
print text_file.read()
text_file.close()

>>> 
What do you want to name your new file? myFile.txt
Enter a line to write to the myFile.txt file >> this is a test

Contents of the new file: this is a test
>>>

hope this helps :)

well, you need to put the .txt extension at the end of the newFile input to get a text file

Sorry, but that's absolutely not true. The file type is *not* distinguished by extension. (It's more of a hint on Windows, and irrelevant on Linux. Don't know about Mac, but I guess it should be similar to *nix.)

Fetch, what exactly is not working? Because you code works for me as is. Did you get an exception? Which one? What was the name you entered when things went wrong? What was the working directory at that time? Do you have write permissions in that directory?

There are certain characters a file name can not have, might depend on the OS. On Unix you have to have permission to write to some of the directories.

Thankyou vegaseat and master of puppets, the problem must have had something to do with the OS because i had imported that module. Now it works without the module. However, i need the program to check if the raw_input filename already exists and if it does, ask the user if he/she wants to replace the existing file. Does anyone have and idea how to do that?

os.path.exists(filename) will return True or False.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.