程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python learning notes_ Day03

編輯:Python

File object

Operation steps :

  1. open
  2. Reading and writing
  3. close

Read text file

(nsd1903) [[email protected] day02]# cp /etc/passwd /tmp/
>>> f = open('/tmp/passwd') # Open file
>>> data = f.read() # Read everything by default
>>> data
>>> print(data)
>>> data = f.read()
>>> data
''
>>> f.close() # Close file
>>> f = open('/tmp/passwd')
>>> f.read(4) # Read 4 byte
'root'
>>> f.read(3)
':x:'
>>> f.readline() # Read a line
'0:0:root:/root:/bin/bash\n'
>>> f.readline()
'bin:x:1:1:bin:/bin:/sbin/nologin\n'
>>> f.readlines() # Read out all the lines , Put it on the list , Each row is an entry in the list
>>> f.close()
# The most popular way to read text files is for loop
>>> f = open('/tmp/passwd')
>>> for line in f:
... print(line, end='')
>>> f.close()

With bytes Way to read files

1 individual 16 Hexadecimal number , It's exactly the same as 4 position 2 Base number :

0b0000 <-> 0x0
0b1111 <-> 0xF

You can read any file with bytes Mode on . When reading the contents of a file , If it's text content , Will be displayed as characters , If it can't be converted to characters , It will show directly 16 Hexadecimal number .

>>> f = open('/tmp/passwd', 'rb')
>>> f.read(4)
b'root'
>>> f.close()
>>> f = open('/bin/ls')
>>> f.read(10) # When reading ,python Trying to convert content into characters , But it failed , Report errors
>>> f.close()
>>> f = open('/bin/ls', 'rb')
>>> f.read(10)
b'\x7fELF\x02\x01\x01\x00\x00\x00'
>>> f.close()

Write a text file

>>> f = open('/tmp/passwd', 'w') # Create or empty files
>>> f.write('hello world!\n') # \n Means line break
13 # Indicates that a total of 13 byte
>>> f.flush() # The default data is written to the cache , Will not immediately synchronize to disk ,flush() Write to disk now
>>> f.writelines(['2nd line.\n', '3rd line.\n'])
>>> f.close() # Close file , Data will also be synchronized to disk

with sentence

Use with Open file ,with After statement end , Files close automatically .

>>> with open('/tmp/passwd') as f:
... for line in f:
... print(line, end='')

Move file pointer

>>> f = open('/tmp/passwd', 'rb')
>>> f.tell() # Returns the file pointer location , The offset from the beginning of the file to the file pointer
0
>>> f.read(5)
b'hello'
>>> f.tell()
5
>>> f.seek(0, 0) # Move the pointer to the beginning of the file
# seek The second parameter is relative position ,0 Beginning of expression ,1 Indicates the current location ,2 End of expression ; The first parameter is the offset
>>> f.seek(-6, 2) # Move the pointer to the end of the file 6 A place
>>> f.close()

practice : Copy files

# Preliminary realization
f1 = open('/bin/ls', 'rb')
f2 = open('/tmp/ls', 'wb')
data = f1.read()
f2.write(data)
f1.close()
f2.close()

Problems with the above code

  • Try to use variables , Don't use... Directly '/bin/ls' Such a direct quantity
  • Variable names should make sense ,f1 and f2 Such a name doesn't make sense
  • When reading data , Read it all in at once , There may be too much data

function

Name a piece of code . If there is a function , need 10 Line code , And this function needs to be in 5 There are three places to reuse . You can encapsulate these function codes into functions , We need to use this function in the future , Just call the function .

When a function is defined , The code will not execute . When you call a function , The code inside the function will execute .

The return value of the function

  • The result of function execution , have access to return Go back
  • If the function does not return sentence , Default return None
  • When a function encounters return When the sentence is , The function will return the result , Stop executing

The parameters of the function

  • The data that the function needs to process , Generally, it is passed by parameters
  • When defining a function , The parameter value is uncertain , Space occupying with a name , It's called a formal parameter 、 Shape parameter
  • When a function is called , Pass specific data to the function , This specific data is the actual parameter used , It's called the actual parameter 、 Actual parameters
  • When a formal parameter is assigned to an argument , It's just a variable assignment
  • The arguments inside the function 、 Variables are local variables , Only available within functions .

Positional arguments

  • stay python in , The positional parameters are saved in sys Modular argv In the list
  • The positional parameters are all passed in the form of characters
(nsd1903) [[email protected] day03]# cat pos.py
import sys
print(sys.argv)
(nsd1903) [[email protected] day03]# python pos.py hao 123
['pos.py', 'hao', '123']

Default parameters

Parameters that provide default values for functions .

  • When you call a function , The ginseng , The value of a formal parameter is the value of an argument passed
  • When you call a function , Don't pass it on , The value of the parameter is the default
>>> def pstar(n=30):
... print('*' * n)
...
>>> pstar(20)
********************
>>> pstar(50)
**************************************************
>>> pstar()
******************************

Function exercises 1:

  • Write a function , Function takes a string
  • Function to remove the space to the left of the string
  • Returns a substring that removes the left-hand space
s1 = ' hello world'

Function exercises 2:

  • Write a function , Function takes a string
  • Function takes the number out of the string
  • Returns the number in a string
s1 = 'a12bcd89xf2340ll'

modular

  • One by .py Ending python A program file is a module
  • Module naming requirements
  • The first character can only be a letter or an underline
  • Other characters can be letters 、 Numbers 、 Underline
  • Case sensitive
  • The module name is python Program file name removal .py The front part of the back
# vim star.py
""" Star module
This module contains a global variable and a function
"""
hi = 'Hello World'
def pstar(n=30):
" Default printing 30 asterisk "
print('*' * n)
# python3
>>> import star
>>> help(star)
>>> star.hi
'Hello World'
>>> star.pstar()
******************************

How to import modules

# Direct import
>>> import time
>>> time.strftime('%Y-%m-%d')
'2019-08-02'
# Import multiple modules , Not recommended
>>> import sys, os, datetime
# Only import some functions in the module
>>> from random import randint, choice
>>> randint(1, 100)
81
>>> choice('+-*/')
'/'
# When importing a module , Alias it
>>> import getpass as gp
>>> gp.getpass()

Module features

  • Each module file has a special variable called __name__
  • Its value can be __main__, It can also be a module name
  • When the module file runs directly , yes __main__
  • When the module runs indirectly ( By import Import ) Is the module name
(nsd1903) [[email protected] day03]# cat foo.py
print(__name__)
(nsd1903) [[email protected] day03]# cat bar.py
import foo
(nsd1903) [[email protected] day03]# python foo.py
__main__
(nsd1903) [[email protected] day03]# python bar.py
foo
 Writing python When you file , Frequently used if __name__ == '__main__'
if __name__ == '__main__' It means :

When .py When the file is run directly ,if name == 'main' The code block below will be run ; When .py When the file is imported as a module ,if name == 'main' The code block below is not run .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved