首页 > 其他分享 >CS50P: 6. File I/O

CS50P: 6. File I/O

时间:2024-07-18 15:56:38浏览次数:13  
标签:CS50P file File student line csv open name

File I/O

list相关函数

python: list

append()

  • 向列表末尾添加元素
list.append(element)

sorted(*, key=None, reverse=False)

  • sorts the list in place, using only < comparisons between items
  • key: eg. key=str.lower() 说明用小写来排序,但是列表还是不变
  • 稳定排序

程序

names = []
for _ in range(3):
    names.append(input("What's your name? "))
for name in sorted(names):
    print(f"hello, {name}")

程序一旦结束,所有信息都会消失,File I/O可以存储信息,便于后续使用

open

open files

Python: open

file = open("name.txt", "w") 

open 以写入的方式打开name.txt文件。如果不存在,就创建一个文件;如果存在,会清空

返回“文件指针”

写入文件

name = input("What's your name? ")
file = open("name.txt", "w")
file.write(name)
file.close()

每次运行程序都从头重写name.txt文件

追加内容

"w" 替换成 "a" (append)

with

自动关闭文件

with open("name.txt", "a") as file:
    file.write(f"{name}\n")

file得到open的返回值

读文件

全部读

with open("name.txt", "r") as file:
    lines = file.readlines()
for line in lines:
    print("hello,", line.rstrip())	#去掉文件换行符

read所有行,存入lines,是一个list

"r" 可省,是默认值

逐行读

with open("name.txt", "r") as file:
    for line in file:
        print("hello,", line.rstrip())

不需要先读所有行,for line in file 可以一行一行地读

排序

names = []
with open("name.txt", "r") as file:
    for line in file:
        names.append(line.rstrip())
for name in sorted(names):
    print(f"hello, {name}")

CSV

CSV stands for "comma separated values"

students.csv文件

Hermione,Gryffindor
Harry,Gryffindor
Ron,Gryffindor
Draco,Slytherin

一列名字,一列房屋,用 , 隔开

读取信息

with open("students.csv") as file:
    for line in file:
        row = line.rstrip().split(',')
        print(f"{row[0]} is in {row[1]}")

split()返回list

设置两个变量接收信息,而非一个list:

name, house = line.rstrip().split(',')
print(f"{name} is in {house}")

排序

存成元素为 dict 的 list

students = []

with open("students.csv") as file:
    for line in file:
        name, house = line.rstrip().split(',')
        student = {}    #student是一个dict
        student["name"] = name
        student["house"] = house
        students.append(student) 

for student in students:
    print(f"{student['name']} is in {student['house']}")

注意:

  1. line 12 中 'name' 用单引号括起来,因为已经使用过双引号

  2. line 6~8 可以换成 student = {"name": name, "house": house}

sort keys

def get_name(student):      #student is a dict
    return student["name"]
for student in sorted(students, key=get_name):
    print(f"{student['name']} is in {student['house']}")

line 3 key=get_name :sorted函数会用list中的每个字典自动帮我们call get_name(student),可以理解为key指示如何排序

另一种写法:

for student in sorted(students, key=lambda student: student["name"]):

lambda function: 未名函数,"Hey Python, here is a function that has no name: Given a student (参数), access their name and return that to the key "

CSV Library

CSV是Python的一个库,Python: CSV

csv.reader

假设csv文件某行有不止一个 , ,可以用 "" 括起来,再调用库

Harry,"Number Four, Privet Drive"
Ron,The Burrow
Draco,Malfoy Manor
import csv
students = []
with open("students.csv") as file:
    reader = csv.reader(file)
    for row in reader:
        students.append({"name": row[0], "home": row[1]})

A reader works in a for loop, where each iteration the reader gives us another row from our CSV file. This row itself is a list, where each value in the list corresponds to an element in that row

因为 row 是一个 list,所以 line 5~6 可写为:

for name, home in reader:
    students.append({"name": name, "home": home})

csv.DictReader

通常csv文件头部是描述 (header information),比如:

name,home
with open("students.csv") as file:
    reader = csv.DictReader(file)
    for row in reader:	#row是字典
        students.append({"name": row["name"], "home": row["home"]})

DictReader 从头到尾,把每一行看作一个 dict 并返回

the compiler will directly access the row dictionary, getting the name and home of each student

row["name"] 需要 .csv 文件中有 name 一栏,并且不要求 namehome 有序

csv.writer

import csv
name = input("What's your name? ")
home = input("Where's your home? ")
with open("students.csv", "a") as file:
    writer = csv.writer(file)
    writer.writerow([name, home])

csv.DictWriter

with open("students.csv", "a") as file:
    writer = csv.DictWriter(file, fieldnames=["name", "home"])
    writer.writerow({"home": home, "name": name})

fieldnames 参数决定了 csv 文件里 name 在前,home 在后,即 line 3 的输入同样会得到先名字再房子

PIL

a python library

Pillow’s documentation of: PIL

import sys
from PIL import Image

images = []

for arg in sys.argv[1:]:
    image = Image.open(arg)
    images.append(image)

images[0].save(
    "costumes.gif", save_all=True, append_images=[images[1]], duration=200, loop=0
)

The last lines of code saves the first image and also appends a second image to it as well, creating an animated gif

loop=0 循环无限次

标签:CS50P,file,File,student,line,csv,open,name
From: https://www.cnblogs.com/chasetsai/p/18309746

相关文章

  • [1036] Extracting hyperlink information from an Excel file
    Certainly!ExtractinghyperlinkinformationfromanExcelfile(specifically.xlsxformat)inPythoncanbedoneusingtheopenpyxllibrary.Let’sdiverightin:Usingopenpyxl:First,makesureyouhavetheopenpyxllibraryinstalled.Ifnot,youcan......
  • [1035] Extract the content from online PDF file or PDF url
    Certainly!WhenworkingwithonlinePDFsusingthepyPDF2libraryinPython,youcanretrievethecontentfromaPDFfilehostedataURL.Let’sexploreacoupleofwaystoachievethis:Usingrequests(Python3.xandhigher):Ifyou’reusingPython3.x......
  • 【OCPP】ocpp1.6协议第5.5章节Clear Charging Profile的介绍及翻译
    目录5.5清除充电配置ClearChargingProfile-概述ClearChargingProfile请求ClearChargingProfile响应操作流程适用场景5.5清除充电配置ClearChargingProfile-原文译文5.5清除充电配置ClearChargingProfile-概述OCPP1.6协议中的第5.5章节主要讲的是“Cl......
  • xlrd.biffh.XLRDError: Excel xlsx file; not supported
    问题描述今天在测试python读取excel文件的时候出现了异常Traceback(mostrecentcalllast):File"E:/worksp_py/hardwary/100day/thirtfive/testxml.py",line5,in<module>wb=xlrd.open_workbook("./test.xlsx")File"E:\Tools\anaconda3......
  • Makefile-只修改了.h头文件,编译为什么不起作用
    Makefile-只修改了.h头文件,编译为什么不起作用?-腾讯云开发者社区-腾讯云(tencent.com) 不知道各位小伙伴是否碰到过这样的情况:一个.c文件include另一个.h头文件,使用Makefile来构建(编译)应用程序。第一次编译、执行,很正常!但是此时,如果修改了.h头文件,再次编译时,就出现......
  • deepspeed训练模型提示:cpu_adam.so: cannot open shared object file: No such file o
    背景本人在安装deepspeed后遇到了这个报错,明眼人一看就是缺库,但是搜索到的解决方案(凌漪_,2023)说是设置一个环境变量,实在是治标不治本,而且对本人来说连标都治不了。其他的博客尚未看到解决此问题的。分析这个so文件理论上应该在安装deepspeed的过程中就自动编译好了,但是......
  • Javascript: Blob, File/FileReader, ArrayBuffer, ReadableStream, Response 转换方
    目录先上图各个ObjectArrayBuffer:Blob:File:FileReader:ReadableStream:Response用法举例ArrayBufferBlob,File,FileReaderReadableStream关于ReadableStream的一点总结Response构造函数Parametersblob()先上图各个ObjectArrayBuffer:1.ArrayBuffer是JavaScript......
  • 从零手写实现 nginx-29-try_files 指令
    前言大家好,我是老马。很高兴遇到你。我们为java开发者实现了java版本的nginxhttps://github.com/houbb/nginx4j如果你想知道servlet如何处理的,可以参考我的另一个项目:手写从零实现简易版tomcatminicat手写nginx系列如果你对nginx原理感兴趣,可以阅读:从零......
  • CS50P: 5. Unit Tests
    assertPython:assert.calculator.py:defmain():x=int(input("What'sx?"))print("xsquaredis",square(x))defsquare(n):returnn+n #刻意为之if__name__=="__main__":main()test_calculator.py:f......
  • 2024-07-16升级问题:调用自带软件打开文件时 android.os.FileUriExposedException
    2024-07-16升级问题:调用手机自带软件打开文件时,出现以下问题:E/AndroidRuntime:FATALEXCEPTION:mainProcess:rs.tabletcropland,PID:10997android.os.FileUriExposedException:file:///storage/emulated/0/arcgis/%E7%9F%B3%E7%8B%AE%E5%B8%82/Attachment/%E7......