Create and append object content instances using Python

Source: Internet
Author: User
This article mainly introduces Python file creation and append file content instances. This article also provides the standard output to the file instance. For more information, see 1. create a new file in Python with an integer ranging from 0 to 9. each number occupies one row:

The code is as follows:


# Python
>>> F=open('f.txt ', 'w') # r read-only, w writable, a Appended
>>> For I in range (0, 10): f. write (str (I) + '\ n ')
...
>>> F. close ()

2. append the file content, with 10 random integers from 0 to 9:

The code is 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 ()

3. append the file content, a random integer from 0 to 9, a row of 10 numbers, 10 rows in total:

The code is as follows:


# Python
>>> Import random
>>> F=open('f.txt ', 'A ')
>>> For I in range (0, 10 ):
... For I in range (): f. write (str (random. randint )))
... F. write ('\ n ')
...
>>> F. close ()

4. export standard output to a file:

The code is as follows:


# Python
>>> Import sys
>>> Sys. stdout = open ("stdout.txt", "w ")


Example:
22nd client profile, and write the final result into a.txt

The code is 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 22 '). 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.