Implement file Read and write
#! /usr/bin/python
File_add = open (' Test.txt ', ' a ')
For I in range (1,5):
File_add.write ("1.1.1.%d 255.255.255.255%d 2.2.2.%d 255.255.255.168 \ n"% (i,i,i))
File_add.close ()
Problems encountered during the period:
1. String formatting problem-Multiple parameters
-sh-4.1#./add.py
Traceback (most recent):
File "./add.py", line 4, <module>
File_add.write ("1.1.1.%d 255.255.255.255%d 2.2.2.%d 255.255.255.168 \ n"%i%i%i)
Typeerror:not enough arguments for format string
-sh-4.1#./add.py
File "./add.py", line 4
File_add.write ("1.1.1.%s 255.255.255.255%d 2.2.2.%s 255.255.255.168 \ n"%i,%i,%i)
^
Syntaxerror:invalid syntax
Access information (http://www.cnblogs.com/vamei/archive/2013/03/12/2954938.html):
When formatting a string, Python uses a string as a template. There are formatting characters in the template that reserve locations for real values and describe the format in which real values should be rendered. Python uses a tuple to pass multiple values to the template, each of which corresponds to a format character. Between the template and the tuple, there is a% number separated, which represents the format operation.
For example: Print ("I ' m%s"). I ' m%d year old "% (' Vamei ', 99))
2. Read and write operation problem-parameters
-sh-4.1#./add.py
Traceback (most recent):
File "./add.py", line 4, <module>
File_add.write ("1.1.1.%d 255.255.255.255%d 2.2.2.%d 255.255.255.168 \ n"% (i,i,i))
Ioerror:file not open for writing
Change File_add = open (' Test.txt ', ' R ') to File_add = open (' Test.txt ', ' W ') to resolve;
However, the contents of the original write text.txt are overwritten each time add.py is run, and if additional write files are required, File_add = open (' Test.txt ', ' W ') is changed to File_add = Open (' Test.txt ', ' a ').
Refer to the following (http://www.cnblogs.com/dkblog/archive/2011/02/24/1980651.html):
open/file Operations
F=open ('/tmp/hello ', ' W ')
#open (path + file name, read-write mode)
#读写模式: R read-only, r+ read/write, W New (overwrites the original file), a append, b binary. Common mode
such as: ' RB ', ' WB ', ' r+b ' and so on
The types of read-write modes are:
RU or Ua opens in read-only mode with universal line-feed support (PEP 278)
W opens in write mode,
A opens in Append mode (starting with EOF and creating a new file if necessary)
R+ Open in read-write mode
w+ Open in read/write mode (see W)
A + opens in read/write mode (see a)
RB opens in binary read mode
WB opens in binary write mode (see W)
AB opens in binary append mode (see a)
Rb+ opens in binary read/write mode (see r+)
Wb+ opens in binary read/write mode (see w+)
Ab+ opens in binary read/write mode (see A +)
Finally, be sure to close () After you remind the open () operation.
Python learning file read/write