Python 实验六 文件访问
生活随笔
收集整理的這篇文章主要介紹了
Python 实验六 文件访问
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
🌴 2022.06.08 下午 實驗
實驗六 文件訪問
文章目錄
- 前言
- 題目一
- 題目二
- 題目三
前言
🎬本文章是 【Python語言基礎】 專欄的文章,主要是上課的隨堂筆記與練習
🔗Python專欄 傳送門
📽實驗源碼已在Github整理
題目一
編寫一個程序,通過鍵盤將曹操的《觀滄海》寫入文本文件gch.txt中
問題分析
將觀滄海保存在listStr列表中,通過with open…as…寫模式,file.write()方法逐行將列表中的數據存入txt文件中
代碼
listStr = [ "觀滄海", "曹操", "東臨碣石,以觀滄海。", "水何澹澹,山島竦峙。", "樹木叢生,百草豐茂。", "秋風蕭瑟,洪波涌起。", "日月之行,若出其中。", "星漢燦爛,若出其里。", "幸甚至哉,歌以詠志。"] with open("gch.txt", "w") as file:for k in listStr:file.write(k+"\n")結果
題目二
創建一個名為grade.csv的文件,通過input()函數向文件中寫入學生相關信息,格式為“姓名,性別,年齡,語文成績,數學成績,英語成績”,當輸入“-1”時結束輸入。統計所有學生的總成績、排序,并寫入新文件statistics.csv中
問題分析
在函數Input()中定義變量,headers[]保存表頭信息,list1[]保存學生信息,將信息寫入grade.csv文件,之后在Cout()函數中利用sorted()方法對總成績排序,然后寫入statisticx.csv文件
代碼
""" @Author:張時貳 @Date:2022年06月08日 @CSDN:張時貳 @Blog:zhangshier.vip """ import csv# 通過input()函數向文件中寫入學生相關信息,格式為“姓名,性別,年齡,語文成績,數學成績,英語成績”,當輸入“-1”時結束輸入 def Input():headers = [ 'Name', 'Sex', 'Age', 'chNum', 'maNum', 'egNum' ]list1 = [ ('李四', '男', 21, 80, 80, 80), ('王五', '男', 22, 95, 95, 95), ('張時叁', '女', 22, 85, 85, 85) ]tu = ()n = Nonewhile (n != '-1'):t1 = str ( input ( "輸入名字:" ) )t2 = str ( input ( "輸入性別:" ) )t3 = int ( input ( "輸入年齡:" ) )t4 = float ( input ( "輸入語文分數:" ) )t5 = float ( input ( "輸入數學分數:" ) )t6 = float ( input ( "輸入英語分數:" ) )tu = (t1, t2, t3, t4, t5, t6)list1.append ( tu )n = input ( '任意鍵回車繼續,輸入 -1 開始寫入:' )try:with open ( "grade.csv", "w", encoding='ANSI', newline='' ) as file:fw = csv.writer ( file )fw.writerow ( headers )fw.writerows ( list1 )print ( "將文件寫入grade.csv成功" )except Exception as ex:print ( ex )print ( "將文件寫入grade.csv失敗" )# 統計所有學生的總成績、排序,并寫入新文件statistics.csv中 def Count():ch = [ ]ma = [ ]chn = 0man = 0list1 = [ ]try:with open ( "grade.csv", "r", encoding='ANSI', newline='' ) as file:fr = csv.reader ( file )list1 = [ li for li in fr ]print ( "讀取文件grade.csv成功" )except Exception as ex:print ( ex )print ( "讀取grade.csv失敗" )try:with open ( "statistics.csv", "w", encoding='ANSI', newline='' ) as file:fw = csv.writer ( file )list1[ 0 ].append ( '總成績' )fw.writerow ( list1[ 0 ] )# 按總成績從小到大排名for x in range ( 1, len ( list1 ) ):list1[ x ].append ( float ( list1[ x ][ 3 ] ) + float ( list1[ x ][ 4 ] ) + float ( list1[ x ][ 5 ] ) )print ( list1[ x ] )list1 = sorted ( list1[ 1: ], key=lambda x: float ( x[ 6 ] ) )fw.writerows ( list1 )print ( "寫入statisticx.csv成功" )except Exception as ex:print ( ex )print ( "寫入statisticx.csv失敗" )Input () Count ()結果
題目三
編寫一個程序,分別將一個數字、字符串、列表、元組、字典和集合寫入一個二進制文件BFVle.dat中,然后從二進制文件BFVle.dat中讀出并顯示
問題分析
定義數字、字符串、列表、元組、字典和集合變量,利用data[]集合將數據保存起來,通過pickle庫中pickle.dump()方法寫操作,pickle.load()方法讀操作,讀文件通過while循環,發生異常時直接拋出
代碼
""" @Author:張時貳 @Date:2022年06月08日 @CSDN:張時貳 @Blog:zhangshier.vip """ import picklenum = 1 # 數字 string1 = "zhangshier.vip" # 字符串 list1 = [ 1.25, 21.06, 0.3, 4.7, 58.1 ] # 列表 tuple1 = (1, 8, 27, 64, 125) # 元組 dict1 = dict ( name="Mary", height=165, weight=51 ) # 字典 set1 = {1, 4, 9, 16, 25} # 集合data = [ string1, list1, tuple1, dict1, set1 ] # 數據with open ( "pickle_file.dat", "wb" ) as pickle_file: # 打開的二進制文件for i in data:pickle.dump ( i, pickle_file ) # 向文件中寫入序列化內容print ( "寫入數據成功!" )with open ( "pickle_file.dat", "rb" ) as pickle_file:# y = pickle.load ( pickle_file ) # 一次只讀一行,利用while()讀多行# print ( y )while 1:try:y = pickle.load ( pickle_file )print ( y )except EOFError:break結果
總結
以上是生活随笔為你收集整理的Python 实验六 文件访问的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 批处理文件语法
- 下一篇: Windows定时自动执行python脚