第八章 模块;第九章 文件

知识点:

(1)模块:用于存储Python代码的文件。可在一个模块中调用另一个模块的代码。若要调用模块,需先使用 import 。

z = ['a','b','c','d','e']
import random
for i in range(10):
    print(random.choice(z))#用.来表示层级关系:random是模块,choice该模块下的函数。

可以自创一个模块,然后调用。

def f(x,y):      #file>save,命名为ss.放在名为practise的文件夹里。完成模块的创建。
    return x**y
import ss       #file>save,命名为ff,同样放在practise的文件夹里。如果ss与ff不在同一个文件夹,会报错

print(ss.f(23))

(2)文件:使用Python处理文件:读文件意味着文件中数据的访问,写文件意味着添加或修改数据。语法:with open ("文件名.格式", "打开模式") as 变量:执行代码

打开模式:"r"代表只读,"w"代表只写,"w+"代表读写。

with open("xx.txt","w") as f:
    f.write("hi from python")#file>save,命名为xx,保留在practice文件夹中。而后可以在practice文件夹中看到xx.txt文件。
with open ("xx.txt","r") as f:  #在另外一个文件中读取xx.txt文件中的内容。两个文件需要在同一个文件夹。
    print(f.read())

(3)Python处理CSV文件。先运行代码,然后再去文件夹用Excel打开test.csv文件,才会看到one,two,three.否则看到的是代码。

import csv


with open("test.csv", "w") as f:
    w = csv.writer(f, delimiter = ",")  #writer方法用于接收一个文件对象和分隔符
    w.writerow(["one","two","three"])   #writerow方法用于写入一行数据

读取CSV文件。所有python文件保存在同一个文件夹,才不会报错。

import csv

with open("test.csv","r") as f:
    r = csv.reader(f, delimiter = ",")
    for row in r:
        print(",".join(row))

 (4)文件路径:在windows系统中,文本路径用斜杠(“ / ”)表示

with open("text_file/file") as file_object:
    contents=file_object.read()
print(contents.rstrip())

(5)逐行读取文件。

file_name="pi_digits"
with open(file_name) as file_object:
    for line in file_object:
        print(line.rstrip())
file_name="pi_digits"
with open(file_name) as file_object:
    lines=file_object.readlines()
for line in lines:
    print(line.rstrip())

(6)写入文件

file_path="text_file/file"
with open(file_path,'w') as f:
    f.write("i love you\n")
    f.write("i hate you\n")
file_path="text_file/file"
#"a":附加模式--不覆盖原文件内容
with open(file_path,'a') as f:
    f.write("hello boy\n")
    f.write("good monring\n")
filename = "guest"
message = "what' your name?"
while True:
    name = input(message)
    if name == "quit":
        break
    print("hello %s" % name)

    with open(filename, "a") as f:
        f.write("%s\n" % name)

 

(7)读写模式“  "r+"

filename="guest"
message="what' your name?"
#读写模式“r+"
with open(filename,"r+") as f:
    f.write(input(message))

 

posted @ 2020-05-08 22:36  jerrygogo  阅读(124)  评论(0编辑  收藏  举报