CS50P 6_File I/O

Save Data in a List, but Run Again...

#save name to names list
names = []

for _ in range(3):
    names.append(input("What's your name? "))

for name in sorted(names):
    print(f"hello, {name}")
$python names.py 
What's your name? Ted
What's your name? Harry
What's your name? Rone
hello, Harry
hello, Rone
hello, Ted

names.py

Save Name Permanently

names.py

# Writes to a new file 

name = input("What's your name? ")

file = open("names.txt", "w") 
file.write(name)
file.close()
$ python names.py 
What's your name? Ted
$ cat names.txt
Ted

Append Data to a File

names.py

# Writes to a new file 

name = input("What's your name? ")

file = open("names.txt", "a")
file.write(f"{name}\n")
file.close()
$ python names.py
What's your name? Ted
$ python names.py
What's your name? Harry
$ cat names.txt
Ted
Harry

Auto Close File

# Adds context manager

name = input("What's your name? ")

with open("names.txt", "a") as file:
    file.write(f"{name}\n")
$ python names.py
What's your name? Ted
$ python names.py
What's your name? Harry
$ cat names.txt
Ted
Harry

names.py

Read Data from a File

# Reads from a file

with open("names.txt") as file:
    lines = file.readlines()

for line in lines:
    print("hello,", line.rstrip())
$ python names.py
hello, Ted
hello, Harry
$ cat names.txt
Ted
Harry

names.py

Read Data from File

# Reads from a file, one line at a time

with open("names.txt") as file:
    for line in file:
        print("hello,", line.rstrip())
$ python names.py
hello, Ted
hello, Harry
$ cat names.txt
Ted
Harry

names.py

CSV File

逗點分格資料的純文字檔案檔案格式

$ code students.csv
張三,123456
李四,135793
王五,243666

Read CSV File

# Reads a CSV file

with open("students.csv") as file:
    for line in file:
        row = line.rstrip().split(",")
        print(f"{row[0]} number is {row[1]}")
$ python names.py
張三 number is 123456
李四 number is 135793
王五 number is 243666

names.py

Read CSV File

# Unpacks a list

with open("students.csv") as file:
    for line in file:
        name, number = line.rstrip().split(",")
        print(f"{name} number is {number}")
$ python names.py
張三 number is 123456
李四 number is 135793
王五 number is 243666

names.py

Python Lambda 函式

匿名函式,不需要定義名稱,只有一行運算式

lambda parameter_list: expression

lambda : 關鍵字

parameter_list : 參數清單

expression : 運算式

Lambda Example

def square(x):
    return x ** 2
square = lambda x: x ** 2
square(2)
4

Lambda Example

def add(x,y):
    return x + y
add = lambda x, y: x + y
print(add(1, 2))
print(add(3, 5))
print(add)
3
8
<function <lambda> at 0x7fada83b1f28>

Lambda Example

def abs_number(x):
    if x >= 0:
        return x
    else:
        return -x
abs_number = lambda x : x if x >= 0 else -x
print(abs_number(10))
print(abs_number(-2))
10
2

Save PIL Image as GIF

CS50P 6_File I/O

By wschen

CS50P 6_File I/O

Learn how to save and retrieve data, work with CSV files, use Python Lambda functions, and save images in different file formats in CS50P 6_File I/O presentation.

  • 126