File method
Write:
#!/usr/bin/env pythonf = open (' Somefile.txt ', ' W ') f.write (' Hello, ') f.write (' world! ') F.close () F = open (' Somefile.txt ', ' R ') print F.read (5)
Hello
Use the basic file method:
#!/usr/bin/env pythonf = open (R ' somefile.txt ') print F.read () f.close () F = open (R ' Somefile.txt ') for I in range (3):p rint STR (i) + ': ' + f.readline () f.close () Import pprintpprint.pprint (open (R ' Somefile.txt '). ReadLines ()) F = open (' Somefile.txt ', ' W ') f.write (' We\nchange\nthis file! ') F.close () F = open (R ' somefile.txt ') print F.read () f.close () F = open (R ' somefile.txt ') lines = F.readlines () f.close () lines [1] = "changed\n" f = open (R ' Somefile.txt ', ' W ') F.writelines (lines) f.close () F = open (R ' somefile.txt ') print f.read () F.close ()
Thisis Atest!0:this1:is a2:test! [' this\n ', ' is a\n ', ' test!\n ']wechangethis file!wechangedthis file!
File Unpacking:
#!/usr/bin/env pythonf = open (R ' Somefile.txt ', ' W ') f.write (' First line\n ') f.write (' Second line\n ') f.write (' third line \ n ') f.close () lines = list (open (' Somefile.txt ')) Print Linesfirst,second,third = open (' somefile.txt ') print Firstprint Secondprint Third
[' First line\n ', ' Second line\n ', ' third line\n '] First Linesecond Linethird Line
Beginning Python from Novice to Professional (8)-File method