Python creates files and appends file content instances
- 2020-04-02 14:18:01
- OfStack
1. Create a new file in Python with integers from 0 to 9 on one line:
#python
>>>f=open('f.txt','w') # r Read only, w Can write, a additional
>>>for i in range(0,10):f.write(str(i)+'n')
. . .
>>> f.close()
Ii. Append the contents of the file to 10 random integers from 0 to 9:
#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()
Iii. The contents of the file are appended. Random integers from 0 to 9, 10 digits in one line, 10 lines in total:
#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. Direct standard output to the file:
#python
>>> import sys
>>> sys.stdout = open("stdout.txt", "w")
Example:
Look at port 22 and write the result to a.t.xt
#!/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()