python File I/O write to another line questions

  • DizzyFoxkit
  • Born
  • Born
  • DizzyFoxkit
  • Posts: 4

Post 3+ Months Ago

alright, so to get to the point my problem lies in a very simple question, using the .write() and .writelines() functions of python, how can you make it so that it write to another line. For example, say I want the strings '123', and '456' on two different lines, so that when you call example.dat for reading, readlines(0) returns 123 and readlines(1) returns 456.
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • this213
  • Guru
  • Guru
  • User avatar
  • Posts: 1260
  • Loc: ./

Post 3+ Months Ago

Code: [ Select ]
fout.write("123\n456\n")

or
Code: [ Select ]
fout.write("123\n")
fout.write("456\n")
  1. fout.write("123\n")
  2. fout.write("456\n")

or
Code: [ Select ]
strings = ["123\n","456\n"]
fout.writelines(strings)
  1. strings = ["123\n","456\n"]
  2. fout.writelines(strings)


In short, you have to add the newline character "\n".
  • DizzyFoxkit
  • Born
  • Born
  • DizzyFoxkit
  • Posts: 4

Post 3+ Months Ago

Quote:
In short, you have to add the newline character "\n".


I thought so too, but whenever I add the newline character in any of the above mentioned ways, readlines(0) and readlines(1) just return [], which i'm taking to mean an empty string. While read() just returns a giant string, though this may be what it does and I'm just being silly. Does it have something to do with the file I'm writing to being a .dat? Or is my understanding of Strings skewed by considering them to be arrays?
  • this213
  • Guru
  • Guru
  • User avatar
  • Posts: 1260
  • Loc: ./

Post 3+ Months Ago

read() reads the whole file at once and returns a single string, so you'd have to split on newlines. readlines() should be returning both lines in an array. readline() (note the "s") reads one line at a time.

There's no hard and fast rule as far as the format of a .dat file. If you don't know what it does or how it's formatted, why are you trying to write to it? Do you even have write permissions to it?
  • DizzyFoxkit
  • Born
  • Born
  • DizzyFoxkit
  • Posts: 4

Post 3+ Months Ago

Im writing to it to figure out what it does. Im also writing to it because if i had the correct hypothesis, it would make it easier than telling the code to splice at /n. I also do have permission to write to it. Your explanation of read() makes sense. If you have annything else to say, than i'd be glad to hear it.

Post Information

  • Total Posts in this topic: 5 posts
  • Users browsing this forum: No registered users and 108 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.