I am trying to read from a file and write out that string to a new file. This is the failing code I have: newFile = file('/home/user/newFile.txt', 'w') inFile = raw_input('Enter a file: ') inFile = file(inFile) open(inFile, 'r+') inFile.write('/home/user/newfile.txt') When run in shell I get: TypeError: coercing to Unicode: need string or buffer, file found
I'd comment that first line out. You are assigning 'newFile' to a text file when it needs to be a string.
Well, lets walk throught this: newFile = file('/home/user/newFile.txt', 'w') It seems you want to open a file at a very specific path for write only. If there are any mistakes in the path, this will fail. Also, you normally use open() for this. Not sure what file() does. inFile = raw_input('Enter a file: ') Get a string from the user and set it to inFile inFile = file(inFile) open(inFile, 'r+') Use the string you just got to represent a path to a file. If there are any mistakes, this will fail. Here you use both file() and open(), so something wrong there. Also, the 'r+' means open the "original" file as read/write. Why would you want to write to the original if doing some sort of copy? inFile.write('/home/user/newfile.txt') Write to the original file the string '/home/user/newfile.txt', which makes little sense.
Take a look at this stuff: http://www.tutorialspoint.com/python/python_files_io.htm
Thanks for the help. I am still struggling. I've come up with some new code that is still not working: userFile = raw_input('Enter a filename: ') ## get a filename from the user as string userFile = file(userFile) ## convert string to file object so it can be open/read userFile.read() ## read the file print 'Is',(userFile),'closed?', userFile.closed ## print whether the file is closed or not newFile = open('sample2.txt', 'w') ## open a new file to which I want to write the contents of the newFile.write(str(userFile)) ## write contents I think I am not opening the file but I don't know why? How do I take the string from raw_input and make it open the file?
On your userFile, you need to open() it before you can read it. Syntax: file object = open(file_name [, access_mode][, buffering]) Look over that I/O tutorial @e.mccormick linked, it has some good info.
Join our real-time social learning platform and learn together with your friends!