WeSeong Log in
← Back to posts
Programming languages

Python file reading and writing, classes

Python file reading and writing, classes

I may continue writing about Python, but for now, let's stop here. Networks or Linux Related posts will be published soon. There are only four Python-related posts, and it’s not even possible to understand Python with these four posts. Since even a single subheading in one of my posts can generate enough discussion to fill several posts, I think you can consider the posts I’ve written so far as a summary or an introduction. Or, you can think of them as “this is the order in which you should study.” So, let’s get started! 🙃


Ⅰ. Overview

In Python FileYou can import or create files. Reading and writing files is more important than you might think, and they can be used in a variety of ways. The functions that are used when reading or writing files are open() There is a function. When reading a file, readline(), readlines() You use the function. When writing a file, write(), writelines() We use functions. They are at the core of object-oriented programming. Class There is a concept. Python also creates objects as classes. PropertiesAnd Action programming. Classes Member variablesAnd MethodsIt consists of creation, operation, and destruction. 'Life cycle'has a special method of the class __del__() Functions and __add__() There are functions. A class is another class. InheritanceIn this case, inheritance means that the relationship between the parent class and the child class is like the way a car wheel belongs to the car.


Built-in functions



Ⅱ. Reading and Writing Python Files

You might wonder why you should learn to read and write files in Python. But reading and writing files It's more important in programming than you might think. For example, when you are working on a web project and need to import and store a large amount of data in a database, automation using Python is well-known. When you generate files from input data during the automation process, or when you read and use Excel, Hangul, PDF, text files, and so on, file reading and writing are used. Of course, it is not possible to do all of the above examples with the content mentioned in this post. There are many ways to use file reading and writing. LibraryIf you have a basic understanding of file reading and writing, I recommend that you study other libraries as well! 😊


※ TIP: If LinuxTogether CLI (Command-Line Interface)If you use it, file reading and writing are more important. Linux is the operating system used when utilizing cloud services, and since the CLI simply transfers data and runs programs in text form, you can read and write files that are only in text form and create automated programs to utilize them. Windows Same GUI (Graphical User Interface)is easy to use with the mouse and keyboard. This is because the CLI does not use graphical elements by default. However, when graphical elements are used, many ResourceThis makes memory management very important, so it's good to know how to read and write files.


Both file reading and writing 3-step processIt goes through. First, open the file. Second, read or write to the file. Finally, close the file.

First, the process of opening a file is an essential step when reading or writing. open() Use the function, and return the value from the open() function File handlersIn this case, the file cannot be read or written immediately, but it is in a state before it is used directly if it is functioning normally.

file = open('경로와 파일이름', '읽기 모드, 쓰기 모드 중 선택', '인코딩 요소')

The open() function has a variety of arguments, but by default, the arguments in the above example are commonly used. Here PathThis is important, because due to the path, you may encounter many errors. 'Read Mode'is basically 'r'You can write it 'Write mode'is 'w'There are also many other modes, so it might be good to explore and use them while studying. Encoding (character set) The element is not required, but depending on the encoding of the file, Korean may be broken. ASCII code, UnicodeIt's good to know the concept, and there are many good posts on this topic, so I recommend you look them up. The encoding we usually use is 'utf-8'That is.


※ TIP: The path Relative pathAnd Absolute pathThere is. A relative path looks for a file to use from the current directory. An absolute path looks for a file to use from the root directory. In a relative path, the current directory is '.\'That's right, the top directory '..\'and can continue to grow. For example, the absolute path for a window is 'C:/User/USER/····' It is structured this way. There are many cases where the path is incorrect and the file cannot be opened, so it requires a lot of practice.


Once you have opened the file, you need to read or write it.

line = file.readline()
lines = file.readlines()
print(line, end="")
결과 출력 ==> '안녕하세요.'
print(lines)
결과 출력 ==> ['안녕하세요.\n', '파일을 읽고 있습니다.\n']

The function used to read files is largely readline()And readlines()In the example above, you may have noticed that readline() reads a text file one line at a time. readlines() puts all the content into a list one line at a time. The important thing here is that when opening a file, the open() function newline You can specify properties, but if you don't specify them, they are set to default '\n' Newline is the default. So when the lines variable is printed, each line is followed by a '\n' newline. Escape charactersYou can see that it contains


※ TIP: Both the readline() and readlines() functions explain how to read a file one line at a time, using the open() function. seek(), tell() related to functions such as Cursor It's good to understand the concepts. There are many well-organized articles, so please refer to them.


text1 = '안녕하세요.' + "\n"
text2 = '이번엔 파일을 작성해볼거에요.' + "\n"
file.write(text1)
file.write(text2)

text_list = ['안녕하세요.\n', '이번엔 파일을 작성해볼거에요.\n', '우와, 리스트로 작성하네요.\n']
file.writelines(text_list)

When writing a file write() Functions and writelines() We use a function. Notably, both the text1 and text2 variables have been appended with newline escape characters. When writing the file, it is important to explicitly specify the newline with the escape character to ensure that the newline is properly inserted. The write() function writes a string, but, writelines() is similar to readlines() above, returning a list of stringsYou can create both at once. Depending on the situation, both can be used, so it's good to know both.


※ TIP: You may wonder how a file can be opened when it doesn't already exist. The path and file name used when writing a file in the open() function is determined by me when I create the file. Location and file name to saveEnter the file name. If a file with the same name already exists at that location, overwrite Be careful! 🥲


Now that we have read or written the file, we need to close the file we opened. If we don't close it, the file handler returned by the open() function will be allocated in memory and remain there. Memory leakageIt can cause slowdowns and should be closed with 'file.close()' when finished.

with open('경로와 파일명', '읽기, 쓰기 모드', '인코딩') as f :
    f.readline(), f.readlines()
    f.write(), f.writelines()

Opening and closing files can be a tedious task, and sometimes you forget to close them when you write long pieces of code. So there's a keyword that makes it easy to do both at once: 'with'However, as in the example above, we can prepend the 'with' keyword to the open() function and treat it as a function. :' After adding the colon, you can specify what action to take inside it. 'as f'If you use the open() function separately, you can use the same read and write functions by specifying the name you want to use after adding 'as' and returning the file handler to the file variable.


Mission: Receive the message to be sent, encrypt the file, and then create a decrypted file from the encrypted file.

I think this mission is useful for both reading and writing files. I'm attaching the sample code right now. You might want to practice it slowly.

#암호화 파일 생성
#메시지 입력
def inputText() :
	lines = []
	while True :
		text = input("메시지 입력 : ")
		if text == "" :
			break
		else :
			lines.append(text)

	return lines

#암호화 파일 생성
def fileCode() :
	lines = inputText()
	with open("C:\\Users\\user\\OneDrive\\바탕 화면\\code.txt", "w", encoding="utf-8") as f :
		for txt in lines :
			for tt in txt :
				ascii = ord(tt)
				
				if tt == ' ' :
					f.writelines(chr(ascii))
				else :
					ascii -= 30000
					f.writelines(chr(ascii))
			f.writelines("\n")

fileCode()

#해독한 파일 생성
#파일 불러오기
def callFile() :
	texts = []

	with open("C:\\Users\\user\\OneDrive\\바탕 화면\\code.txt", "r", encoding="utf-8") as f :
		while True :
			line = f.readline()
			if line == '' :
				break
			else :
				line = line.split('\n')[0]
				texts.append(line)

	return texts

#복호화
def descrambling() :
	lines = callFile()

	with open("C:\\Users\\user\\OneDrive\\바탕 화면\\des.txt", "w", encoding="utf-8") as f :
		for txt in lines :
			for tt in txt :
				ascii = ord(tt)
				
				if tt == ' ' :
					f.writelines(" ")
				else :
					ascii += 30000
					f.writelines(chr(ascii))
			f.writelines("\n")

descrambling()

※ TIP: The reason why '\\' appears twice in the path is because it is recognized as an escape character, which prevents proper path specification. By adding it once more, we are expressing that it is a character to be used in the path, not an escape character.


I also share the mission that was difficult in this class. It is automating the server configuration file that will be used in the network and Linux later. The concept is not yet clear, so I couldn't find the rules properly and configured the logic. I think it would be good to try it once.


There are two configuration files below.

#다음은 setup.cfg 파일의 설정임

#WEB config
LISTEN : 8001;
SERVER_NAME : www.myserver.com;
proxy_pass : http://1.2.3.4:8080;

#WAS config
DB...

#server.cfg설정 파일
server {
	listen	80;
	server_name	localhost;
	
	location / {
		root /usr/share/nginx/html;
		index index.html index.html;
	}
}

Mission: Load the setup.cfg file and store the properties such as listen, server_name, and proxy_pass, along with their settings. Then load the server.cfg file and change the values to match the corresponding properties. For example, listen is changed from 80 to 8001. If there is no property in the setup.cfg file, add it to the 'location / {}' setting.

#config파일경로
def configPath() :
	path = input("경로 : ")
	return path

#config 파일 불러오기
def config(path) :
	path = path + "\\setup.cfg"
	cfg = {}
	with open(path, "r", encoding="utf-8") as f :
		while True :
			#데이터 가공 key, value로 구분(ex. 'LISTEN_PORT : 8001;\n'에서 마지막 ';\n'빼고)
			#":"기준으로 split 후 'LISTEN_PORT'는 key, '8001'은 value
			line = f.readline()

			if line.count(":") > 0 :
				index = line.find("\n")
				line = line[:index]
				idx = line.find(":")
				key = line[:idx].lower().strip()
				value = line[idx+1:].lower().strip()

				cfg[key] = value

			if line == "" :
				break
	print("불러오기 성공")
	return cfg

#server.cfg 파일 불러오기
def server(path, cfg) :
	path = path + "\\server.cfg"
	keyList = list(cfg.keys())

	with open(path, "r+", encoding="utf-8") as f :
		lines = f.readlines()

		for i in range(len(lines)) :
			for key in keyList :
				if lines[i].lower().find(key.lower()) >= 0 :
					line = lines[i].split("\t")
					line[-1] = cfg[key] + "\n"
					chgLine = "\t".join(line)
					lines[i] = chgLine
					keyList.remove(key)
				elif lines[i].lower().find(key.lower()) < 0 :
					line = lines[i].split("\t")

					if 'location / {\n' in line :
						newLine = ['\t', key, cfg[key]+"\n"]
						chgLine = "\t".join(newLine)
						lines.insert(i+1, chgLine)

		#파일의 맨 처음으로 커서이동
		f.seek(0, 0)
		#파일의 전체 내용 새로 쓰기
		f.writelines(lines)
		
	print("변환 성공")

#main
def main() :
	path = configPath()
	cfg = config(path)
	server(path, cfg)

main()

This is an example code that I think requires more study. I hope you can write better code.



Ⅲ. Python Classes

Before writing about a class Object-oriented programmingIt is so important, difficult, and lengthy that it would take several books to explain it. I cannot cover it all in this post. So, please consider it a summary or an introduction and read it.


First of all, Objectis a term used in programming to refer to numerous things. Things are literally It could be a person, a car, an animal, a smartphone, a tablet, and so on. What PropertiesAnd ActionJust as a person has hands and feet and performs actions such as walking, eating, and sleeping, and a car has wheels, an engine, and a battery and performs actions such as moving forward, moving backward, and playing music, here the person and the car are objects, while hands and feet, wheels, engines, and batteries are properties, and walking, eating, sleeping, moving forward, moving backward, and playing music are actions.


Python allows you to use objects that have already been created. In Python, Stringis one object Operations on the string property, such as find(), lower(), and upper()We have the len() function, which is also a method of the object.


※ TIP: It may be easier to understand if you think of methods as simple functions or actions.


A class is a kind of DrawingBut what I want to create The properties of an object are defined as member variables, and the actions are defined as methods.and can be used in the program.

class 클래스명 :
    #멤버 변수
    def 메소드명 :
    def __init__(self) :
        #생성자

Declare and define it in this way.

class car :
    car_name = '자동차'

    def __init__(self, car_name) :
        self.car_name = car_name

    def go(self) :
        print(self.car_name + '가 앞으로 간다.')

For example, if we assume that there is a Car class, the car name is both an attribute and a member variable. go() There is a function that means the car is moving forward.


※ TIP: __init__() The method is a constructor. It is called unconditionally as soon as the object is created. The constructor can clearly indicate what kind of object the class is, by taking the values of member variables as parameters and initializing them. To understand the constructor, 'Life cycle'It's good to understand. There's a lot of good material on the subject. Absolutely necessary We recommend that you search for it.


genesis = car('제네시스')
genesis.go()
출력 결과 ==> '제네시스가 앞으로 간다.'

When creating and using a class, it typically has this structure. You declare variable names according to the class, and if the class has a constructor with parameters, you provide the parameters. If not, you can omit them. Now, you can call the class's methods with these variable names to construct the program logic.


As opposed to the __init__() method __del__() A method that is called when a class has been fully used and is no longer needed. When a class is declared and defined, it is allocated memory space. As you create programs, many classes are used. To manage memory space efficiently, in languages like Java, Garbage CollectionThere is a way to automatically destroy classes, and Python also has this. So there is no need to write a separate __del__() method.


With a unique method __add__() There is a method. Previously, lists could be added and multiplied, and objects can be added using a method.

class car :
    car_name = ''
    def __add__(self, other) :
        print("객체", self.car_name, "과", other.car_name, "가 친구가 되었습니다.")

genesis = car()
genesis.car_name = "제네시스"
k3 = car()
k3.car_name = "K3"

genesis + k3
출력 결과 ==> 객체 제네시스 와 K3 가 친구가 되었습니다.

As in the example above Two objects (classes)By adding them, we can use objects of the same type together. Just as we defined 'Genesis' and 'K3' separately, in addition to the constructor, we can define a class It is not recommended to access member variables directly. Direct access to member variables makes the code longer and more difficult to maintain when using the class. One of the important reasons for using objects is Data, internal structure (implementation) protectionfor 'Capsule'However, this is violated, and the logic inside the object can be exposed externally.


Actually, following Class inheritance, the four main characteristics of objects (inheritance, abstraction, polymorphism, encapsulation) There are many concepts to understand, and it is impossible to cover them all, and it may take a long time, so we recommend that you continue to study and find and study relevant good articles.



Reviews

I studied Python, which is getting more and more difficult. Especially, lists, tuples, dictionaries, and functions from the previous session are all essential and can be used to create something, but what makes programming more advanced? Classes are what make it so. I remember that I searched a lot for the concept of object-oriented programming because I didn’t really understand it. I can’t say that I fully understand it now, but I feel proud that I can use it more widely than before. I’m looking forward to studying networking and Linux in the future, and I think I need to work harder. 😄