1.
import tempfile
import os
import sys
fd = tempfile.NamedTemporaryFile(delete=False)
print(fd.name) ;
cmd = 'ls -l %s' % fd.name
os.system(cmd)
#os.system('ls -l %s' % fd.name)
fd = open(fd.name, 'wb')
fd.write(b'Hello World!\n')
fd.close()
open(fd.name, 'rb')
print(fd.read())
=====================================================
2.
fd = open ('myfile.txt', 'r')
print=(fd.read())
fd.close()
====================================================
3.
반드시 파일을 닫아야 하는데 까먹을때 이런 형식 씀
with open('myfile2.txt', 'w') as fd:
fd.write('Hello WOrld\n')
위랑 똑같은 코드
fd = open('myfile2.txt', 'w')
fd.write("Hello World2\n")
fd.close()
==================================================
4. content = """Hello! Welcome to demofile.txt
This file is for testing purposes.
Good Luck!"""
fd = open('t.txt', 'w')
fd.write(content)
fd.close()
fd = open('t.txt', 'r')
line = fd.readline()
print(line)
fd.close
readlines(여러줄)은 rstrip이랑 보통 같이 가는 경우가 많음
fd = open('t.txt', 'r')
lines = fd.readlines()
for cont in lines:
print(cont.rstrip())
fd.close
fd = open('t.txt', 'r')
lines = fd.read(15)
print(lines)
fd.close()
================================================
5.
import os
if os.path.exists('t.txt'):
os.remove("t.txt")
else:
print('continue')
if not os.path.isdir(path):
os.mkdir(path)
[실습]
6.
[실습] 파일을 생성하고, 생성된 파일의 내용을 넣고, 삭제한다.
■ 생성할 파일의 이름: /test/test.txt
* (주의) 혹시나 /test 디렉토리가 없으면 생성
=> os.path.isdir(path) + os.mkdir(path)
■ 생성된 파일(/test/test.txt)의 내용:
반갑습니다.
python 개발자 여러분
한살 더 드셨죠!
올 한해는... 행복한 가득한 한해가 되었으면 합니다.
=> open(file, mode)
■ 생성한 파일(/test/test.txt)의 내용 확인
=> read(file, mode)
■ 생성한 파일 삭제 후 정상적으로 삭제가 잘 되었다면 파일이 삭제 되었다는 메세지를 출력한다.
=> os.path.isfile(path) + os.remove(path)
import os
contents = """반갑습니다.
파이썬 개발자 여러분 한살 더 드셨죠!
올 한해는 행복한 가득한 한해가 되었으면 합니다."""
fd = open('test.txt', 'w')
fd.write(contents)
fd = open('test.txt', 'r')
lines = fd.readlines()
for cont in lines:
print(cont.rstrip())
fd.close
if os.path.exists('test.txt'):
os.remove("test.txt") ; print()
print("파일이 삭제되었습니다")
or
import os
contents = """반갑습니다.
파이썬 개발자 여러분 한살 더 드셨죠!
올 한해는 행복한 가득한 한해가 되었으면 합니다.
"""
os.system('mkdir -p /test')
with open('/test/test.txt', 'w') as fd:
fd.write(contents)
with open('/test/test.txt') as fd:
print(fd.read())
if os.path.exists('/test/test.txt'):
os.remove('/test/test.txt')
print('The file is removed.')
[객체지향]
클래스
7.
class Singer: # 클래스 첫번째 글자는 대문자
def sing(self):
return "LaLaLa~~"
Taeji = Singer() # 인스턴스와 붙혀주면 오브젝트가 된다
print(Taeji.sing())
Ricky = Singer()
print(Ricky.sing())
=================================
8. 오브젝트 생성
class Myclass:
x = 5
print(Myclass)
p1 = Myclass()
print(p1.x)
====================================
9.
class Person:
def __init__(self, name, age): # 이닛은 기본적으로 처리해야 하는 부분. 클래스의 인자값은 이닛으로 받는다.
self.name = name
self.age = age
def myfun(self): # 클래스 안에 들어있는 메소드(함수)는 첫 인자로 self를 받는다.
print("Hello, my name is " + self.name)
print("I'm %d years old." % self.age)
p1 = Person('John', 37)
p1.myfun()
or
p1 = Person("John", 37) # 선언해서 메모리 공간을 할당 받고
p1.age = 38
print(p1.age)
p1.myfun()
del p1 # 삭제
print(p1)
=====================================================================
10. 디아블로 캐릭 만들기
class Amazon:
strength = 20
dexterity = 25
vitality = 20
energy = 15
def attack(self):
return '=> Jab'
def exercise(self):
self.strength += 2
self.dexterity += 2
self.vitality += 3
self.energy += 5
-----
import Diablo
jane = Diablo.Amazon()
print(jane.strength)
print(jane.attack())
eve = Diablo.Amazon()
eve.exercise()
print(eve.strength)
----------------------------------------
11. 상속
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fname, lname, year):
super().__init__(fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome to Korea")
print("%d" % self.graduationyear)
x = Student('One-J', 'E', 2020)
print(x.graduationyear)
x.welcome
=================================================
12.
* person.py
class Person:
eyes = 2
nose = 1
mouth = 1
ears = 2
arms = 2
legs = 2
def eat(self):
print("냠냠")
def sleep(self):
print("쿨쿨")
def talk(self):
print("주저리주저리")
------------------
* student.py
import person
class Student(person.Person):
def study(self):
print("열공 열공")
x = Student()
print(x.eyes)
x.eat()
x.study()
* import 방식 2
from person import Person
class Student(Person):
*
import person
x = person.Person()
print(x.eyes)
x.sleep()
[모듈]
1. 덧셈
def nsum(a, b):
return a + b
def safe_sum(a, b):
if type(1) != type(b):
print("Error")
return
else:
result = nsum(a,b)
return result
--------------------
import module1
#from module1 import sum
#print(module1.nsum(3, 4))
print(module1.safe_sum(3, 4))
=====================================================
2. 도서관
class Book:
def __init__(self):
print("객체가 만들어 졌습니다")
def input_data(self, title, price, author):
self.title = title
self.price = price
self.author = author
def check_data(self):
print('제목 : ', self.title)
print('가격 : ', self.price)
print('저자 : ', self.author)
--------
>>> b = bookstore.Book()
객체가 만들어 졌습니다
>>> b.input_data('정보보안전문가', '29000원', 'takudaddy')
>>> b.check_data()
제목 : 정보보안전문가
가격 : 29000원
저자 : takudaddy
=================================================
3. 냉장고
class Fridge:
isOpened = False #클래스 객체들
foods = []
def open(self):
self.isOpened = True
print('냉장고 문이 열렸습니다')
def put(self, thing):
if self.isOpened == True:
self.foods.append(thing)
print("음식을 넣었습니다")
else:
print("냉장고 문을 열어주세요")
def close(self):
self.isOpened == False
print('냉장고 문을 닫았습니다.')
class Food:
pass
-------
import Fridge
LG = Fridge.Fridge()
LG.open()
LG.put('Apple')
LG.close()
print(LG.foods)
LG.open()
LG.put('elephant')
LG.close()
print(LG.foods)
======================================================
4. 커피머신
5. 엘레베이터
728x90
'정보보안공부 > 정보보안전문과정' 카테고리의 다른 글
정보보안 과정 Day 76-1 : 암호학 이론 (0) | 2020.12.23 |
---|---|
정보보안 과정 Day76 : Python 마지막 (0) | 2020.12.23 |
정보보안 과정 Day 74 : Python 3 (0) | 2020.12.21 |
정보보안 과정 Day 73 : Python2 (0) | 2020.12.18 |
정보보안 과정 Day72 : Python 시작 (0) | 2020.12.17 |