Python Create files and append file content instances _python

Source: Internet
Author: User

First, create a new file in Python with an integer from 0 to 9, one for each number:

Copy Code code as follows:

#python
>>>f=open (' F.txt ', ' W ') # R Read Only, W writable, a append
>>>for i in range (0,10): F.write (str (i) + ' \ n ')
.  . .
>>> F.close ()

Second, the file content is appended, from 0 to 9 of 10 random integers:

Copy Code code as follows:

#python
>>>import Random
>>>f=open (' F.txt ', ' a ')
>>>for i in range (0,10): F.write (str (random.randint (0,9))
.  . .
>>>f.write (' \ n ')
>>>f.close ()

Third, the contents of the file appended, from 0 to 9 of random integers, 10 digit line, a total of 10 lines:

Copy Code code as follows:

#python
>>> Import Random
>>> f=open (' f.txt ', ' a ')
>>> for I in Range (0,10):
.  .     . For I in Range (0,10): F.write (str (random.randint (0,9))
.  .     . F.write (' \ n ')
.  . .
>>> F.close ()

Iv. directing standard output to file:

Copy Code code as follows:

#python
>>> Import Sys
>>> sys.stdout = open ("Stdout.txt", "W")

Example:
View the 22 port condition and write the result to A.txt
Copy Code code as follows:

#!/usr/bin/python
#coding =utf-8
Import OS
Import time
Import Sys
F=open (' a.txt ', ' a ')
F.write (Os.popen (' netstat-nltp | grep '). Read ())
F.close ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.