\n doesn't work

A forum for general discussion of the Python programming language.

\n doesn't work

Postby HTHVampire » Thu May 16, 2013 12:58 pm

Code: Select all
# Open a file
fo = open("test.txt", "wb")
fo.write( "Python is a great language. \nYeah its great!!!\n");

# Close opened file
fo.close()


This is the code I tried to create a text file. When I open the test.txt, the statement "Yeah its great!!!" is not in a new line, why is it so?
any wrong with my code? Thanks for your guides!
HTHVampire
 
Posts: 9
Joined: Sun Apr 14, 2013 1:31 pm

Re: \n doesn't work

Postby bcuz » Thu May 16, 2013 1:19 pm

You can use something other than "wb" to write to a file. Try searching for this different way.

Edit: Also want to point out that this question is better suited for the General Coding Help section of the forum.
bcuz
 
Posts: 4
Joined: Wed May 15, 2013 2:48 pm

Re: \n doesn't work

Postby setrofim » Thu May 16, 2013 1:40 pm

Use "w" mode rather "wb" when opening the file. By default, Python will translate the "\n" into the correct sequence for your OS; the "b" prevents this, so with "b" you're writing the literal "\n" (character with ASCII code 10) rather than the line break for your OS (which for Windows is actually "\r\n").
setrofim
 
Posts: 288
Joined: Mon Mar 04, 2013 7:52 pm

Re: \n doesn't work

Postby metulburr » Thu May 16, 2013 1:43 pm

either write to the file with 'w' mode, or use windows line breaks
Code: Select all
'\r\n'
New Users, Read This
OS Ubuntu 14.04, Arch Linux, Gentoo, Windows 7/8
https://github.com/metulburr
steam
User avatar
metulburr
 
Posts: 1562
Joined: Thu Feb 07, 2013 4:47 pm
Location: Elmira, NY

Re: \n doesn't work

Postby HTHVampire » Thu May 16, 2013 2:12 pm

Thanks for all the guides and advices given! I appreciate that! :D
HTHVampire
 
Posts: 9
Joined: Sun Apr 14, 2013 1:31 pm


Return to General Discussions

Who is online

Users browsing this forum: No registered users and 4 guests