Python学习记录-基础4

1 模块

模块是一个包含所定义的函数和变量的文件,其后缀名是.py。可以被别的程序引入,以使用该模块中的函数等功能。

In [1]: import sys
In [2]: sys.path
Out[2]: 
['','/usr/local/bin',...'/home/hill/.ipython']
#另一种方法
In [1]: from sys import path
In [2]: sys.path  #NameError  
In [3]: path
Out[3]: 
['','/usr/local/bin',...'/home/hill/.ipython']
#另一种方法
In [1]: from sys import *
In [2]: sys.path  #NameError
In [3]: path
Out[3]: 
['','/usr/local/bin',... '/home/hill/.ipython']
#还可以重命名
In [1]: from sys as s
In [2]: s.path
Out[2]: 
['','/usr/local/bin',... '/home/hill/.ipython']

如果需要在模块被引入时,模块中的某一程序块不执行,可用__name__属性来使该程序块仅在该模块自身运行时执行。

#!/usr/bin/python3
# Filename: using_name.py
if __name__ == '__main__':
   print('程序自身在运行')
else:
   print('我来自另一模块')
#每个模块都有一个__name__属性,当其值是'__main__'时,表明该模块自身在运行,否则是被引入
#使用dir来获取某一模块包含的函数
In [4]: dir()
Out[4]: 
['In', 'Out', '_', '_3', '__', '___', '__builtin__', '__builtins__',...,
 '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'warnoptions']

包:管理 Python 模块命名空间的形式,采用"点模块名称"。一个模块的名称是 A.B, 那么他表示一个包 A中的子模块 B
       在文件夹​​​​​目录中包含一个叫做 __init__.py 的文件,则当前目录下的模块文件会被认作是一个包。以目录名为包名。
       __init__.py为空时,仅仅是把这个包导入,不会导入包中的模块
       在__init__.py文件中,定义一个__all__变量,用于控制着 from 包名 import *时导入的模块,只会导入all里面包含的模块(在这个文件中写入的语句在调用包时会被执行)

__all__ = ["echo", "surround", "reverse"]

2 文件

Linux系统中的一切都是文件。文件的读取:需要指定模式。

In [1]: cd Desktop/
/home/hill/Desktop
In [2]: f = open('test.py','r')  # open ( filename, mode )
In [3]: str = f.read();print(str)
list2=['huang','wen','han']
if 'huang' in list2
    print(list2[0])
In [4]: f = open('test.py','r')
In [5]: str = f.readline();print(str)
list2=['huang','wen','han']
#迭代读取每行
In [6]: f = open('test.py','r')
In [7]: for line in f:
   ...:     print(line,end='')
   ...:     
list2=['huang','wen','han']
if 'huang' in list2
    print(list2[0])
#按行读取
In [8]: f = open('test.py','r')
In [9]: str=f.readlines(2);print(str)
["list2=['huang','wen','han']\n"]
In [10]: str=f.readlines(1);print(str)
["if 'huang' in list2\n"]
In [11]: f.close()  #关闭文件

文件的写入及其他:

In [1]: cd Desktop/
/home/hill/Desktop
In [2]: f = open('text.txt','a') #追加
In [3]: f.write('screw you!')
Out[3]: 10  #返回写入的字符数
In [4]: f.close()
In [5]: cat text.txt
screw you!
#写入其他类型需要转换先
In [6]: f = open('text.txt','a')
In [7]: list = ['boy','next','door']; s=str(list); f.write(s)
Out[7]: 23
In [8]: tup=('aha',18); s=str(tup); f.write(s)
Out[8]: 11
In [9]: f.close()
In [10]: cat text.txt
screw you!['boy', 'next', 'door']('aha', 18)

其他方法:查看

3 文件操作实例(复制并添加)

In [1]: f_old = open('text_old.txt','r');content = f_old.read()
In [2]: f_new = open('text_new.txt','w');f_new.write(content)
Out[2]: 205
In [3]: f_old.close();f_new.write('\nAnd now, the twilight of my life,\
   ...: this understanding has passed into contentment.')
Out[3]: 82
In [4]: f_new.close()
In [5]: cat text_new.txt
When I was a young man,
I had liberty, but I did not see it.
I had time, but I did not know it.
And I had love, but I did not feel it.
Many decades would pass before I understood the meaning of all three.

And now, the twilight of my life,this understanding has passed into contentment.

4 文件os模块

用来处理文件和目录。查看

#/home/hill/Desktop/rename.py
#/home/hill/Desktop/123
import os
folder_name = input("Please input the folder's name you need to rename:\n")
file_name = os.listdir(folder_name)
os.chdir(folder_name)
for name in file_name:
    print(name)
    os.rename(name,"han-"+name)
os.chdir('/home/hill/Desktop')
file_name = os.listdir(folder_name)
print(file_name)

hill@virtual-machine:~/Desktop$ python3 rename.py
Please input the folder's name you need to rename:
123
2.txt
1.txt
3.txt
['han-3.txt', 'han-2.txt', 'han-1.txt']

5 异常、错误

两种错误:语法错误和异常。以下是语法错误:

In [1]: while True print("hello")
  File "<ipython-input-1-6baa8a44e01a>", line 1
    while True print("hello")
                   ^
SyntaxError: invalid syntax

语法是正确的,在运行期检测到的错误被称为异常:

In [2]: 1/0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-2-9e1622b385b6> in <module>()
----> 1 1/0

ZeroDivisionError: division by zero
>>> 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

异常处理:try语句、抛出异常

>>> while True:
        try:  #尝试执行错误语句
            x = int(input("Please enter a number: "))  #没有异常时执行
            break
        except ValueError:  #出现异常时的处理
            print("Oops!  That was no valid number.  Try again   ")
        except (RuntimeError, TypeError, NameError):
            pass
        except Exception as ret:  #此举会捕获到上面except语句没有捕获到的所有异常并作为ret返回
            print(ret)
        else:  #没有异常才会执行的功能
            print('ojbk')
        finally:  #可选语句,无论再任何情况下都会执行
            print('Goodbye, world!')
#raise语句抛出一个异常
>>> raise NameError('s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: s

猜你喜欢

转载自blog.csdn.net/muerjie5669/article/details/81384040