Exception handling, copy depth, basic file operations

First, exception handling

Abnormalities are divided into syntax errors and logic errors

1, unusual species

1.1 Common abnormal

  • AttributeError no attempt to access an object tree, such as foo.x, but no property x foo
  • IOError input / output is abnormal; substantially not open file
  • ImportError package or module can not be introduced; substantially path problem or error name
  • IndentationError syntax error (subclass); the code is not properly aligned
  • IndexError subscript index out of sequence boundaries, such as when only three elements of x, x is trying to access [. 5]
  • KeyError trying to access key does not exist in the dictionary
  • KeyboardInterrupt Ctrl + C is pressed
  • NameError use a variable has not been given an object
  • SyntaxError Python code is illegal, the code does not compile (personally think it's a syntax error, wrong)
  • TypeError incoming object type does not conform with the requirements of
  • UnboundLocalError trying to access a local variable has not been set, basically due to a global variable otherwise the same name leads you to think that it is being accessed
  • ValueError incoming caller does not expect a value, even if the value of the type is correct

2, exception handling

After 2.1 preventive treatment

If the error condition is unpredictable, you need to use try ... except: processing after an error

#基本语法为
try:
    被检测的代码块
except 异常类型:
    try中一旦检测到异常,就执行这个位置的逻辑
    
#  举例
try:
    f = [
        'a',
        'a',
        'a',
        'a',
        'a',
        'a',
        'a',
    ]
    g = (line.strip() for line in f)
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))
except StopIteration:
    f.close()

2.2 Universal exception handling: Exception

Other less than basic, Exception is everything

s1 = 'hello'
try:
    int(s1)
except Exception as e:
    print(e)

Second, the data type classification

Distinguished by the number of stored-value

Number of stored-value type of data
A single value Integer, float, string
Multiple values Lists, dictionaries, tuples, collection

Distinguished by the variable immutable

Variable or immutable type of data
variable Lists, dictionaries, collections
Immutable Integer, floating point, string, a tuple

Distinguished by order-disorder

Ordered or unordered type of data
Ordered Strings, lists, tuples
Disorderly Dictionaries, collections

Access to distinguish between types

Access Type type of data
direct interview Integer, float
Sequential access (sequence type) Strings, lists, tuples
Access key value (mapping type) dictionary

Three, python copy depth

1 copy

a copy of the object is list1 list2, element change any data type within list1, list2 will follow the change, because the list is a variable type

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = l1

l1.append('g')
print(l1)  # ['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)  # ['a', 'b', 'c', ['d', 'e', 'f'], 'g']

2, shallow copy

A package for an import: import copy, list2 = copy.copy (list1), list2 list1 shallow copy of the object is immutable data type element in list1 changes, List2 unchanged; variable data element type is changed in the list1 , list2 change will follow

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.copy(l1)

l1.append('g')
print(l1)   # ['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)   # ['a', 'b', 'c', ['d', 'e', 'f']]

l1[3].append('g')
print(l1)   # ['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)   # ['a', 'b', 'c', ['d', 'e', 'f', 'g']]

3, deep copy

A package for an import: import copy, list2 = copy.deepcopy (list1), list2 list1 deep copy of the object is immutable data type element in list1 changes, List2 unchanged; variable data element type is changed in the list1 , list2 will not change. That list1 list2 will never change because of change

import copy

l1 = ['a', 'b', 'c', ['d', 'e', 'f']]
l2 = copy.deepcopy(l1)

l1.append('g')
print(l1)   # ['a', 'b', 'c', ['d', 'e', 'f'], 'g']
print(l2)   # ['a', 'b', 'c', ['d', 'e', 'f']]

l1[3].append('g')
print(l1)   # ['a', 'b', 'c', ['d', 'e', 'f', 'g'], 'g']
print(l2)   # ['a', 'b', 'c', ['d', 'e', 'f']]

Fourth, the basic file operations

1, open the file

f = open(r'/Users/mac/desktop/jupyter/pythonCourseware/32.txt')
print(f)

Open the file should be noted that the encoding format, the file must open the My Computer join encoding = 'UTF-8' in the open

f = open(r'/Users/mac/desktop/jupyter/pythonCourseware/32.txt',encoding='UTF-8')
print(f)

2, the read data

After opening the file, not only takes up memory, he also corresponds to the operating system to open the file, the equivalent of using a text editor to open a file. And we said we manipulate the file just to read and write, thus opening the file is not an end, to read and write is the goal, then we try how to read and write files.


f = open(r'/Users/mac/desktop/jupyter/pythonCourseware/32.txt', mode='r')  # read模式打开文件

data = f.read()
print(data)   # 读取文件内容,向操作系统发起读请求,会被操作系统转成具体的硬盘操作,将内容由硬盘读入内存

f.close()  #  关闭文件 # 由于Python的垃圾回收机制只回收引用计数为0的变量,但是打开文件还占用操作系统的资源,所以我们需要回收操作系统的资源资源
# del f 只是回收变量f

3, writing data

# write模式打开文件
f = open(r'/Users/mac/desktop/jupyter/pythonCourseware/32.txt', mode='w')
f.write("""name = 'nick'
pwd = '123'""")
f.close()
f = open(r'/Users/mac/desktop/jupyter/pythonCourseware/32.txt', mode='r')
data = f.read()
print(data)

Fifth, the absolute and relative paths

1, the absolute path

  • Absolute path from the Windows system drive letter (C:, D :) began to write a full path.
  • macos system write a complete path from the root directory (/ Users) begins.

2, the relative path

Relative to the currently executing file folder where to start looking.

f = open('32.txt')  # 32.txt与该.md文档同路径位置

Guess you like

Origin www.cnblogs.com/zhuangyl23/p/11312175.html