Tutorial on File and Directory Access in Python
0
komentar
Some Basic File Operations A list of Python file operations can be obtained through the Python dir() command: >>> dir(file) [’__class__’, ’__delattr__’, ’__doc__’, ’__getattribute__’, ’__hash__’, ’__init__’, ’__iter__’, ’__new__’, ’__reduce__’, ’__reduce_ex__’, ’__repr__’, ’__setattr__’, ’__str__’, ’close’, ’closed’, ’encoding’, ’fileno’, ’flush’, ’isatty’, ’mode’, ’name’, ’newlines’, ’next’, ’read’, ’readinto’, ’readline’, ’readlines’, ’seek’, ’softspace’, ’tell’, ’truncate’, ’write’, ’writelines’, ’xreadlines’] Following is an overview of many of those operations. I am beginning in a directory /a, which has a file x, consisting of a bc def a file y, consisting of uuu vvv
and a subdirectory b, which is empty. 1 >>> f = open(’x’) # open, read-only (default) 2 >>> f.name # recover name from file object 3 ’x’ 4 >>> f.readlines() 5 [’a\n’, ’bc\n’, ’def\n’] 6 >>> f.readlines() # already at end of file, so this gets nothing 7 [] 8 >>> f.seek(0) # go back to byte 0 of the file 9 >>> f.readlines() 10 [’a\n’, ’bc\n’, ’def\n’] 11 >>> f.seek(2) # go to byte 2 in the file 12 >>> f.readlines() 13 [’bc\n’, ’def\n’] 14 >>> f.seek(0) 15 >>> f.read() # read to EOF, returning bytes in a string 16 ’a\nbc\ndef\n’ 17 >>> f.seek(0) 18 >>> f.read(3) # read only 3 bytes this time 19 ’a\nb’ If you need to read just one line, use readline(). Starting with Python 2.3, you can use a file as an iterator: 1 >>> f = open(’x’) 2 >>> i = 0 3 >>> for l in f: 4 ... print ’line %d:’ % i,l[:-1] 5 ... i += 1 6 ... 7 line 0: a 8 line 1: bc 9 line 2: def. Download free Tutorial on File and Directory Access in Python here
and a subdirectory b, which is empty. 1 >>> f = open(’x’) # open, read-only (default) 2 >>> f.name # recover name from file object 3 ’x’ 4 >>> f.readlines() 5 [’a\n’, ’bc\n’, ’def\n’] 6 >>> f.readlines() # already at end of file, so this gets nothing 7 [] 8 >>> f.seek(0) # go back to byte 0 of the file 9 >>> f.readlines() 10 [’a\n’, ’bc\n’, ’def\n’] 11 >>> f.seek(2) # go to byte 2 in the file 12 >>> f.readlines() 13 [’bc\n’, ’def\n’] 14 >>> f.seek(0) 15 >>> f.read() # read to EOF, returning bytes in a string 16 ’a\nbc\ndef\n’ 17 >>> f.seek(0) 18 >>> f.read(3) # read only 3 bytes this time 19 ’a\nb’ If you need to read just one line, use readline(). Starting with Python 2.3, you can use a file as an iterator: 1 >>> f = open(’x’) 2 >>> i = 0 3 >>> for l in f: 4 ... print ’line %d:’ % i,l[:-1] 5 ... i += 1 6 ... 7 line 0: a 8 line 1: bc 9 line 2: def. Download free Tutorial on File and Directory Access in Python here
0 komentar:
Post a Comment