1

I am on a windows machine and am trying to write a couple thousand lines to a text file using ipython. To test this I am just trying to get some text to appear in the file.

my code is as follows:

path="\Users\\*****\Desktop" with open(path+'newheaders.txt','wb') as f: f.write('new text') 

This question (.write not working in Python) is answered and seems like it should have solved my issue but when I open the text file it is still blank.

I tested the file using the code below and the text appears to be there.

with open(path+'newheaders.txt','r') as f: print f.read() 

any ideas?

3
  • One comment - you should be opening the file 'wt' not 'wb'. Also, in the path you have a double \ - is that intentional? When you say 'when I open the text file it is still blank' - how are you opening it? In the next sentence you say you tested the file and the text appears to be there - I'm confused, does the created file have the expected text in it or not? Commented Dec 1, 2015 at 15:34
  • Try to delete this file and try again. Are you sure the file gets written at all? in your example I do not see '/' delimiter between path and file name. Hope you have it in real script. Commented Dec 1, 2015 at 15:46
  • 1
    The doubls '\\' is intentional. The file was not being created but I had somehow created one earlier while playing around with the code so I was opening a blank file that already existed but was not being written to. The wb was not an issue but the '/' deliminator was. It works now, thank you! @baldr I cannot mark your answer as correct because it is in a comment! Commented Dec 2, 2015 at 15:13

1 Answer 1

3

This 'should' work as written. A few things to try (I would put this in a comment but I lack sufficient reputation):

  1. Delete the file and make sure the program is creating the file
  2. Try writing as 'wt' rather than binary to see if we can narrow down the problem that way.
  3. Remove all the business with the path and just try to write the file in the current directory.

What text editor are you using? Is it possible it's not refreshing the blank file?

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

1 Comment

I am using notepad. The 'wt' was not an issue as I explained in the comments above. Removing the paths would have solved the issue though. I am using Spyder and need to define a path, but the path was the issue either way!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.