in [105]:F1 = open ('/tmp/passwd ', ' r+ ') read/write mode on
in [106]: F1.next () read a line, next read down, will not move the line indicator
OUT[106]: ' root:x:0:0:root:/root:/bin/bash\n '
In [107]: F1.seek (0,2) offset from the end of the file line (2) position 0 (0), F1.seek (0) back to the beginning
In [109]: F1.tell () View file location (bytes)
OUT[109]: 1576
in [+]: F1.write (' New line.\n ') Add a line
In [F1.readline]: read one line, move line indicator
OUT[112]: "
In [129]: F1.closed decide whether to close
OUT[129]: False No
In [up]: F1.close () Close
In [133]: f1.closed
OUT[133]: True is
Example: Writes the result of a power operation from 1 to 10 to Test.txt
F1 = open ('/tmp/test.txt ', ' w+ ')
For i**2-I in Range (1,11):
F1.write (str (line) + ' \ n ')
F1.flush ()
F1.close ()
Writes directory/ext The file list results to a file test1.txt
F1 = open ('/tmp/test1.txt ', ' w+ ')
Import OS
L1 = Os.listdir (' etc ') #列出目录下的文件
F1.writelines (L1) #将字符串列表内容写入到文件, cannot write data of type Integer.
F1.flush ()
F1.close ()
Note: If you want to add a newline character \ n to each file, you can define it as follows:
F3=open ('/tmp/test3.txt ', ' w+ ')
L2 = [i+ ' \ n ' for I in Os.listdir (' etc ')]
F3.writelines (L2)
Example: input content to file
#!/usr/local/bin/python27
#
Import OS
Import Os.path #加载模块
Filename= '/tmp/test.txt '
If Os.path.isfile (filename): #判断是否有文件filename
f1 = open (filename, ' A + ') #追加打开模式
While True:
line = Raw_input (' Enter something>> ') #交互输入模式
if line = = ' Q ' or line = = ' Quit ':
Break
F1.write (line+ ' \ n ')
F1.close ()
Example: Pointers
Pointer: Open a file, iterate print, the pointer will go to the end, the second time you print, you need to restore the pointer to the beginning
In [2]: f1 = open ('/etc/passwd ', ' R ')
In [3]: F1:
...: Print line,
...: print ' =================== '
...:
Root:x:0:0:root:/root:/bin/bash
===================
Bin:x:1:1:bin:/bin:/sbin/nologin
===================
Daemon:x:2:2:daemon:/sbin:/sbin/nologin
In [5]: F1.tell ()
OUT[5]: 1576
In [6]: F1.seek (0) #需要将指针恢复到最开始
In [7]: F1:
Print line,
print ' =================== '
...:
Root:x:0:0:root:/root:/bin/bash
===================
Python Basics (4)--file object, pointer, Os,os.path module