Python-Ref > Using files > Reading and writing files > Writing files
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Writing files

How to create a file and fill it with content.
To open a file for writing one uses the same method a when reading files, only the second argument to file is different.
The content of the file is then writen using the write or writelines methods of the file object.
Expand/Shrink
Zdroj: (fileio6-1.py)
  1   f = file( "tryout.txt", "w")   # open file "tryout.txt" for "w"riting
  2   
  3   f.write("Hi there.")        # write something to the file
  4   f.write("How do you do?")   # write something more
  5   
  6   f.close()  # close the file
Hi there.How do you do?
Doba běhu: 21.5 ms
Contrary to what one would expect, the method writelines does not add new-line characters at the end of individual lines. This is in order to be consistent with the readlines method.
Expand/Shrink
Zdroj: (fileio6-2.py)
  1   f = file( "tryout.txt", "w")   # open file "tryout.txt" for "w"riting
  2   
  3   lines1 = ["first line.", "second line.", "the third one."]
  4   lines2 = ["first line.\n", "second line.\n", "the third one.\n"]
  5   
  6   f.writelines( lines1)    # write all the lines from a sequence to f
  7   f.writelines( lines2)    # write all the lines from a sequence to f
  8   
  9   f.close()  # close the file
first line.second line.the third one.first line.
second line.
the third one.
Doba běhu: 21.1 ms