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

Python Experiment 6 file access

編輯:Python

This article has participated in 「 New people's creation ceremony 」 Activities , Start the road of nuggets creation together .

2022.06.08 Afternoon experiment

Experiment six File access

Preface

This article is 【Python Language foundation 】 Column articles , Mainly the notes and exercises in class
Python special column Portal
The experimental source code has been in Github Arrangement

Topic 1

Write a program , Through the keyboard, Cao Cao's 《 Watch the sea 》 Write text file gch.txt in

Problem analysis

Save guancanghai in listStr In the list , adopt with open…as… Write mode ,file.write() Method to store the data in the list row by row txt In file

Code

listStr = [
" Watch the sea ",
" Cao Cao ",
" East of Jieshi , To see the sea .",
" The water is not clear , Yamashima wins .",
" There are many trees , A hundred grasses are luxuriant .",
" The autumn wind is bleak , The flood surged up .",
" A trip to the sun and the moon , If out of it .",
" The stars are brilliant , If out of it .",
" Fortunately , Sing to chant ."]
with open("gch.txt", "w") as file:
for k in listStr:
file.write(k+"\n")

result

Topic two

Create a file called grade.csv The file of , adopt input() Function to write student related information to a file , The format is “ full name , Gender , Age , Chinese achievement , Math scores , English scores ”, When the input “-1” When the end of input . Count the total scores of all students 、 Sort , And write a new file statistics.csv in

Problem analysis

In function Input() Define variables in ,headers[] Save header information ,list1[] Save student information , Write the information grade.csv file , After the Cout() Function using sorted() Method to sort the total score , And then write statisticx.csv file

Code

""" @Author: Zhang Shier @Date:2022 year 06 month 08 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
import csv
# adopt input() Function to write student related information to a file , The format is “ full name , Gender , Age , Chinese achievement , Math scores , English scores ”, When the input “-1” When the end of input 
def Input():
headers = [ 'Name', 'Sex', 'Age', 'chNum', 'maNum', 'egNum' ]
list1 = [ (' Li Si ', ' male ', 21, 80, 80, 80), (' Wang Wu ', ' male ', 22, 95, 95, 95), (' Zhangshisan ', ' Woman ', 22, 85, 85, 85) ]
tu = ()
n = None
while (n != '-1'):
t1 = str ( input ( " Input name :" ) )
t2 = str ( input ( " Enter gender :" ) )
t3 = int ( input ( " Enter the age :" ) )
t4 = float ( input ( " Enter the Chinese score :" ) )
t5 = float ( input ( " Enter math score :" ) )
t6 = float ( input ( " Enter English scores :" ) )
tu = (t1, t2, t3, t4, t5, t6)
list1.append ( tu )
n = input ( ' Press enter to continue , Input -1 Start writing :' )
try:
with open ( "grade.csv", "w", encoding='ANSI', newline='' ) as file:
fw = csv.writer ( file )
fw.writerow ( headers )
fw.writerows ( list1 )
print ( " Write files to grade.csv success " )
except Exception as ex:
print ( ex )
print ( " Write files to grade.csv Failure " )
# Count the total scores of all students 、 Sort , And write a new file statistics.csv in 
def Count():
ch = [ ]
ma = [ ]
chn = 0
man = 0
list1 = [ ]
try:
with open ( "grade.csv", "r", encoding='ANSI', newline='' ) as file:
fr = csv.reader ( file )
list1 = [ li for li in fr ]
print ( " Read the file grade.csv success " )
except Exception as ex:
print ( ex )
print ( " Read grade.csv Failure " )
try:
with open ( "statistics.csv", "w", encoding='ANSI', newline='' ) as file:
fw = csv.writer ( file )
list1[ 0 ].append ( ' Total score ' )
fw.writerow ( list1[ 0 ] )
# Rank according to the total score from small to large 
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 ( " write in statisticx.csv success " )
except Exception as ex:
print ( ex )
print ( " write in statisticx.csv Failure " )
Input ()
Count ()

result

Topic three

Write a program , Put a number 、 character string 、 list 、 Tuples 、 The dictionary and collection are written to a binary file BFVle.dat in , Then from the binary file BFVle.dat Read and display

Problem analysis

Define numbers 、 character string 、 list 、 Tuples 、 Dictionary and set variables , utilize data[] Collections save data , adopt pickle In the library pickle.dump() Method write operation ,pickle.load() Method read operation , Read the file through while loop , Thrown directly when an exception occurs

Code

""" @Author: Zhang Shier @Date:2022 year 06 month 08 Japan @CSDN: Zhang Shier @Blog:zhangshier.vip """
import pickle
num = 1 # Numbers 
string1 = "zhangshier.vip" # character string 
list1 = [ 1.25, 21.06, 0.3, 4.7, 58.1 ] # list 
tuple1 = (1, 8, 27, 64, 125) # Tuples 
dict1 = dict ( name="Mary", height=165, weight=51 ) # Dictionaries 
set1 = {1, 4, 9, 16, 25} # aggregate 
data = [ string1, list1, tuple1, dict1, set1 ] # data 
with open ( "pickle_file.dat", "wb" ) as pickle_file: # Open binary 
for i in data:
pickle.dump ( i, pickle_file ) # Write content to the serialized file 
print ( " Write data successfully !" )
with open ( "pickle_file.dat", "rb" ) as pickle_file:
# y = pickle.load ( pickle_file ) # Read only one line at a time , utilize while() Read multiple lines 
# print ( y )
while 1:
try:
y = pickle.load ( pickle_file )
print ( y )
except EOFError:
break

result


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