import random
import os
### file write, read, delete if exist
def main():
# with as를 사용하면 파일을 사용한 뒤 자동으로 파일 객체를 닫음
with open('my_file.txt', 'w') as f:
for _ in range(10):
f.write('a' * random.randint(0, 100))
f.write('\n')
lens = [len(x) for x in open('my_file.txt')]
print(lens)
if os.path.exists('my_file.txt'):
os.remove('my_file.txt')
print('my_file.txt deleted')
else:
print('The file does not exist')
if __name__ == '__main__':
main()
#결과
[74, 61, 90, 58, 97, 35, 11, 4, 6, 26]
my_file.txt deleted
import os
### 줄단위로 Read, Write
def main():
ls = ['안녕\n', '세계\n']
with open('hello.txt', 'w') as f:
f.writelines(ls)
with open('hello.txt', 'r') as f:
rls = f.readlines()
print(rls)
print('=' * 10)
# for loop로 줄 단위 읽기
with open('hello.txt', 'r') as f:
for l in f:
print(l.strip('\n'))
if os.path.exists('hello.txt'):
os.remove('hello.txt')
print('my_file.txt deleted')
else:
print('The file does not exist')
if __name__ == '__main__':
main()
#결과
['안녕\n', '세계\n']
==========
안녕
세계
my_file.txt deleted
def read_file(file_path: str) -> [str]:
file = None
try:
file = open(file_path)
except OSError:
print(f"Error! Couldn't open the file at path {file_path}.")
else:
lines = []
for line in file:
lines.append(line)
return lines
finally:
if file != None:
file.close()
text = read_file("myfile.txt")
if text != None:
print(text)
# 결과
['hello there!']
# Reading a file
path = "C:\\Users\\...\\2024-11-07"
fn = "myfile.txt"
# 방법 1)
fileref = open(path + "\\" + fn, "r")
contents = fileref.read()
fileref.close()
print(f"방법 1: {contents}")
# 방법 2
with open(path + "\\" + fn, "r") as fo:
contents = fo.read()
print(f"방법 2: {contents}")
# 결과
방법 1: hello there!
방법 2: hello there!
# Finding a File in your Filesystem
# myFiles
# │
# ├─otherFiles
# │ ├─extraData
# │ └─────data4.txt
# ├─allProjects
# │ ├─Mydata
# │ ├─────data2.txt
# │ ├─────data3.txt
# │ ├─myProject
# │ ├─────myProgram.py
# │ └─────data1.txt
path = "C:\\Users\\SKTelecom\\UserApps\\PyScripter\\MyPrj\\2024-11-07"
fn = "squares.txt"
with open(path + "\\" + fn, "w") as fw:
for num in range(10):
square = num * num
fw.write(str(square))
fw.write('\n')
with open(path + "\\" + fn, "r") as fo:
contexts = fo.read()[:10]
print(contexts)
# 결과
0
1
4
9
16
# CSV
# Comma Separated Values
#
# The CSV format says that values are going to be separated by
# comma and it says that every line of the file will have the
# same structure.
#
# "Name","Sex","Age","Team","Event","Medal"
# "A Dijiang","M","24","China","Basketball","NA"
# "Edgar Lindenau Aabye","M","34","Denmark/Sweden","Tug-Of-War","Gold"
# "Christine Jacoba Aaftink","F","21","Netherlands","Speed Skating, 1500M","NA"
olympians = [("John Aalberg", 31, "Cross Country Skiing"),
("Minna Maarit Aalto", 30, "Sailing"),
("Win Valdemar Aaltonen", 54, "Art Competitions"),
("Wakako Abe", 18, "Cycling")]
path = "C:\\Users\\...\\2024-11-07"
fn = "reduced_olympics.csv"
outfile = open(path + "\\" + fn, "w")
# output the header row
outfile.write('Name,Age,Sport')
outfile.write('\n')
# output each of the rows:
for olympian in olympians:
row_string = '{},{},{}'.format(olympian[0], olympian[1], olympian[2])
outfile.write(row_string)
outfile.write('\n')
outfile.close()
import os.path
print(f'{fn} is exist: {os.path.isfile(path + "\\" + fn)}')
print("")
with open(path + "\\" + fn, "r") as fo:
contents = fo.read()
print(contents)
# 결과
reduced_olympics.csv is exist: True
Name,Age,Sport
John Aalberg,31,Cross Country Skiing
Minna Maarit Aalto,30,Sailing
Win Valdemar Aaltonen,54,Art Competitions
Wakako Abe,18,Cycling
path = "C:/Users/.../MyPrj/2024-11-07"
fn = "baseball.txt"
teams = ['Houston Astros', 'Seattle Mariners', 'Oakland Athletics',
'Los Angeles Angels', 'Texas Rangers']
with open(path + "//" + fn, "w") as fw:
for team in teams:
fw.write(team + "\n")
with open(path + "//" + fn, "r") as fr:
teams = fr.readlines()
for team in teams:
print(team, end='')
print(f"The file is closed? {fr.closed}")
# 결과
Houston Astros
Seattle Mariners
Oakland Athletics
Los Angeles Angels
Texas Rangers
The file is closed? True
# Reading in non-text files
# - Dozens of other file formatgs exist that are not text
# - Attempting to read them in results in an error
# All files are a sequence of bytes
# - Every file in your computer is stored as a sequence of bytes
# - A single byte consists of 8 bits
# - A bit is either 0 or 1
# - All files are a sequence of 0s and 1s
# - More info in formal text
# Reading in files as binary
# - Set second argument to rb (read binary)
# - By default it is rt (read text)
# Bingo 보드에서 각각의 열, 각각의 행, 대각선 추출하기
board = [[50, 98, 65, 14, 47],
[0, 22, 3, 83, 46],
[87, 93, 81, 84, 58],
[40, 35, 28, 74, 48],
[45, 99, 59, 37, 64]]
def get_rows(board):
return [set(rows) for rows in board]
def get_cols(board):
cols = []
for i in range(5):
s = set()
for j in range(5):
s.add(board[j][i])
cols.append(s)
return cols
def get_diag(board):
s1, s2 = set(), set()
for i in range(5):
s1.add(board[i][i])
s2.add(board[4-i][i])
return [s1, s2]
def get_all_combos(boards):
board_combos = []
for board in boards:
rows = get_rows(board)
cols = get_cols(board)
diag = get_diag(board)
cur_combos = rows + cols + diag
board_combos.append(cur_combos)
return board_combos
rows = get_rows(board)
print(f"len of rows: {len(rows)}")
print(rows)
cols = get_cols(board)
print(f"len of cols: {len(cols)}")
print(cols)
diags = get_diag(board)
print(f"len of diags: {len(diags)}")
print(diags)
# 결과
len of rows: 5
[{65, 98, 14, 47, 50}, {0, 3, 46, 83, 22}, {81, 84, 87, 58, 93}, {35, 40, 74, 48, 28}, {64, 99, 37, 45, 59}]
len of cols: 5
[{0, 40, 45, 50, 87}, {98, 99, 35, 22, 93}, {65, 3, 81, 59, 28}, {37, 74, 14, 83, 84}, {64, 46, 47, 48, 58}]
len of diags: 2
[{64, 74, 81, 50, 22}, {35, 45, 47, 81, 83}]
# import os
# from os import path
# import shutil
# from shutil import make_archive
# from zipfile import ZipFile
# with open("c://windows//temp//myfile.txt", 'w') as f:
# f.write("hello...")
# f.write("\n")
# if path.exists("c://windows//temp//myfile.txt"):
# get the path to the file
# src = path.realpath("c://windows//temp//myfile.txt")
# make a backup copy by appending "bak" to the name
# dst = src + ".bak"
# shutil.copy(src, dst)
# renamin the original file
# os.rename("c://windows//temp//myfile.txt", "c://windows//temp//newfile.txt")
# put things into a ZIP archive
# root_dir, tail = path.split(src)
# shutil.make_archive("archive", "zip", root_dir)
# more fine-grained control over ZIP files
# with ZipFile("c://windows//temp//testzip.zip", "w") as newzip:
# newzip.write("c://windows//temp//newfile.txt")
# newzip.write("c://windows//temp//myfile.txt.bak")
import os
base_path: str = "c:\\windows\\temp\\"
target_fn: str = "practice.txt"
os.chdir(base_path)
print(os.getcwd())
with open(target_fn, 'w+') as f:
f.write("This is a test string")
print(os.listdir())
import shutil
help(shutil.move)
# 삭제도 가능하지만 영구 삭제이므로
# send2trash 같은 외부 모듈 사용을 추천
os.chdir("c:\\Users\\")
for folder, sub_folders, files in os.walk("c:\\windows\\debug\\"):
print(f"Current looking at {folder}")
print("The subfolders are: ")
for sub_f in sub_folders:
print(f"\t Sub_folder: {sub_f}")
print("the files are: ")
for f in files:
print(f"\t File: {f}")
# 결과
c:\windows\temp
['FXSAPIDebugLogFile.txt', 'FXSTIFFDebugLogFile.txt', 'IpcGBufferCwaServer_1_20340', 'practice.txt']
Help on function move in module shutil:
move(src, dst, copy_function=<function copy2 at 0x00000230CBCDCFE0>)
Recursively move a file or directory to another location. This is
similar to the Unix "mv" command. Return the file or directory's
destination.
If dst is an existing directory or a symlink to a directory, then src is
moved inside that directory. The destination path in that directory must
not already exist.
If dst already exists but is not a directory, it may be overwritten
depending on os.rename() semantics.
If the destination is on our current filesystem, then rename() is used.
Otherwise, src is copied to the destination and then removed. Symlinks are
recreated under the new name if os.rename() fails because of cross
filesystem renames.
The optional `copy_function` argument is a callable that will be used
to copy the source or it will be delegated to `copytree`.
By default, copy2() is used, but any function that supports the same
signature (like copy()) can be used.
A lot more could be done here... A look at a mv.c shows a lot of
the issues this implementation glosses over.
Current looking at c:\windows\debug\
The subfolders are:
Sub_folder: WIA
the files are:
File: mrt.log
File: msert.log
File: netlogon.log
File: NetSetup.LOG
File: PASSWD.LOG
File: sammui.log
Current looking at c:\windows\debug\WIA
The subfolders are:
the files are:
File: wiatrace.bak.log
File: wiatrace.log
import pathlib
file_sizes = []
home = pathlib.Path(r"c:\windows\temp")
for path in home.glob('*'):
file_sizes.append(path.stat().st_size)
print(file_sizes)
# list comprehension 사용
file_sizes_lc = [path.stat().st_size for path in home.glob('*')]
print(file_sizes_lc)
# generator expression 사용
file_sizes_ge = (path.stat().st_size for path in home.glob('*'))
print(file_sizes_ge)
print(list(file_sizes_ge))
# 결과
[0, 0, 1049160, 6414, 21, 20104]
[0, 0, 1049160, 6414, 21, 20104]
<generator object <genexpr> at 0x00000279F016B100>
[0, 0, 1049160, 6414, 21, 20104]
import pathlib
import csv
target_path = pathlib.Path("c:\\windows\\temp\\my_file.csv")
print(target_path)
with target_path.open('w', newline='') as target_file:
writer = csv.writer(target_file)
writer.writerow(['column', 'data', 'headings'])
for data in [['1', 'apple', 'fruits']]:
writer.writerow(data)
print("finished writing", target_path)
# 결과 (my_file.csv)
column,data,headings
1,apple,fruits
# Paths in Python
# ===============
# A path is a string that represents the location of a file or
# directory in a file system.
#
# Types of Paths:
# - Absolute Path:
# specifies the exact location of a file or directory from
# the root directory.
# - Relative Path:
# specifies the location of a file or directory relative
# to the current working directory.
댓글 영역