WeSeong Log in
← Back to posts
Programming language

Reading and writing Python files, classes

Reading and writing Python files, classes

While there may be more to say about Python, for now, I'll stop here. Network or Linux A related post will be published soon. There are only four posts related to Python, and it's simply not possible to understand the entire language based on just these four. Because a single sub-title from one of my posts can generate enough discussion to cover multiple posts, I would like you to consider all the posts I've shared as a summary or introduction. Alternatively, you can think of them as a guide on how to study effectively. Let's begin! 🙃


I. Overview

Using Python FileThese can be retrieved or generated. Reading and writing files is more important than you might think, and it can be used in a variety of ways. The functions used for both reading and writing files are: open() The function is present. When reading a file: readline(), readlines() It uses a function. When writing files, write(), writelines() It is a fundamental concept in object-oriented programming. Class There's a concept behind this. Similarly, Python creates objects from classes. AttributeEgg Action The program is based on this. The class is Variable for membersWow MethodIt is composed of three main stages: creation, action, and destruction. "Life Cycle"It possesses a special method within the class. __del__() Functions and __add__() The function exists. The class inherits from another class. InheritanceHowever, inheritance, in this context, refers to the relationship between a parent class and a child class, similar to how a car wheel belongs to the car.


Built-in functions



II. Reading and Writing Python Files

It might seem strange to learn how to read and write files using Python. However, reading and writing files is It's surprisingly important in programming. For example, when working on a web project and needing to import and store a large amount of data in a database, Python-based automation is commonly used. This involves reading and writing files, such as Excel, Word, PDF, and text files, during the automation process, either to create files from the input data or to import and utilize existing files. However, it's important to note that the examples mentioned in this article do not cover all aspects of file reading and writing. There are many... LibraryIf you already understand the basics of file reading and writing, I recommend exploring other libraries to expand your knowledge! 😊


※ TIP: If LinuxTogether CLI (Command-Line Interface)If you are using Linux, file reading and writing are particularly important. Linux is an operating system often used with cloud services, and because the Command Line Interface (CLI) simply transmits data in text form and allows you to run programs, you can read and write files that are only in text format and create automated programs to use them. Windows The same GUI (Graphical User Interface)It can be easily used with a mouse and keyboard. Unlike command-line interfaces (CLIs), which typically don't use graphical elements, this interface relies on them, which can lead to ResourcesThis becomes particularly important, and effective memory management is crucial. Therefore, it's beneficial to understand how to read and write files effectively.


Both reading and writing files Three-step processThis involves [specific actions or processes]. First, open the file. Second, read or write to the file. Finally, close the file.

First, the process of opening a file is one that must be completed whether you are reading or writing to it. open() Using a function to open() and return its result File handlerThis allows you to receive the data. However, you cannot immediately read or write to the file; instead, the file is in a state where it is ready for you to use directly, assuming it functions correctly.

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

The `open()` function has various arguments, but the arguments shown in the example are commonly used. PathThis is important because the path can lead to many errors. "Reading Mode"Essentially, 'r'and I can write it "Writing mode"is "w"I will write it down. In addition, there are many other modes, so it would be beneficial to explore and use them while studying. Encoding (character set) While not essential, the encoding setting can sometimes cause Korean characters to display incorrectly depending on the file's encoding. ASCII code, UnicodeSince there are many helpful articles available on this topic, I recommend that you look for them. The encoding methods we typically use are: 'utf-8'It is.


※ Tip: The route is Opposite routeWow Absolute pathThe relative path finds the file that can be accessed from the current directory. The absolute path finds the file that can be accessed from the root directory. In the relative path, the current directory is '.'It refers directly to the parent directory. "...and it could continue to rise. In the case of absolute paths, for example, Windows... 'C:/User/USER/····' It is structured this way. There are many instances where the path is incorrect and the file cannot be opened, so sufficient practice is necessary.


Now that you've opened the file, you need to either read it or write to it.

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

First, the functions used to read files can be broadly categorized as: read()Egg readlines()This utilizes the `readline()` function, which reads a text file line by line. The `readlines()` function, on the other hand, reads the entire content into a list, one line at a time. The key difference here is that when using `open()`, newline You can specify the attribute, but if you don't specify one, it will use the default. '\n' The default value for line breaks is newline. Therefore, when the `lines` variable is printed, each element will be represented by `\n`. Escape characterYou can see that it's inside.


※ TIP: Both the `readline()` and `readlines()` functions demonstrate how to read a file line by line using the `open()` function. search(), display() Related to functions such as "and," "or," "not," etc. As I grew It would be helpful to understand the concept. There are many well-written articles available for reference.


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

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

When saving a file write() Functions and writelines() It utilizes functions. A notable feature is that both `text1` and `text2` variables have been given newline escape characters. When writing to a file, it's crucial to use the escape character to ensure that the newline characters are properly interpreted and displayed. The `write()` function writes a string, but, writelines() functions similarly to readlines(), returning a list of strings.Both can be written at once. They can be used in different situations, so it's good to be familiar with both.


*TIP: You might wonder how to open a file that doesn't even exist yet. When using the `open()` function to write to a file, the path and filename I provide are the ones I used when creating the file. Desired location to save and file name.Enter the file name. If the same file name already exists in that location, Covering up Please pay attention! 🥲


Now that the file has been read or written, it's necessary to close the file that was opened. If the file is not closed, the file handle returned by the `open()` function will remain allocated in memory, causing issues. Memory leakageThis can cause performance issues and slow down the application. To prevent this, always close files using the `file.close()` method when you are finished with them.

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

Opening and closing files can sometimes be a more complex task than you might think. Additionally, when writing long code, it's easy to forget to close files. Fortunately, there's a keyword that simplifies this process, allowing you to handle it all at once. "with"However, as shown in the example above, add the "with" keyword before the "open()" function, and use it like a function. ':' After adding a colon, please describe the action you want to perform. A notable point is: "as f"If you use the `open()` function separately, you can use the same functions for reading and writing by specifying the desired name after using the `as` keyword, just as if the file handler was returned to the `file` variable.


Task: Receive a message to be sent, encrypt the message, and then create a decrypted version of the encrypted file.

I believe this mission is beneficial for learning both file reading and writing. This time, I'm including an example code directly. It would be helpful 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 double use of '\\' in the path is because it is recognized as an escape character, which prevents the correct path from being specified. Adding it again ensures that it is used as a path character, not an escape character.


I'd also like to share the challenging task I encountered in this class. It involves automating the server configuration files that will be used in future studies, specifically for networking and Linux. However, I'm still struggling to grasp the concepts and haven't been able to find the right rules or build the logic effectively. I'm sharing it here because I think it might be helpful for others.


There are two configuration files provided 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;
	}
}

Task: Load the `setup.cfg` file and store properties such as `listen`, `server_name`, and `proxy_pass`, along with their corresponding values. Then, load the `server.cfg` file and modify the values according to the matching properties. For example, the value of `listen` is changed from 80 to 8001. If a property is not found in the `setup.cfg` file, it is added within 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 of code that I believe could be improved. I would appreciate it if you could write better code.



Ⅲ. Python Classes

Before writing an article about the class, Object-oriented programmingIt's a topic that requires a substantial amount of reading and understanding, and is covered in multiple books. This post cannot cover everything. Therefore, I recommend reading it as a summary or introductory guide.


First, ObjectThis is a term used in programming to refer to a wide variety of objects. By "objects," we mean It could be a person, a car, an animal, a smartphone, a tablet, and so on. Which AttributeEgg ActionJust as humans have hands and feet, and can walk, eat, and sleep, so too do cars have wheels, an engine, and a battery, and can move forward, backward, and play music. In this analogy, humans and cars are objects. Hands, feet, wheels, engines, and batteries are properties, while walking, eating, sleeping, moving forward, moving backward, and playing music are actions.


In Python, this allows you to use pre-existing objects. Python's StringIt can be treated as a single entity. The "text" property, which includes operations like find(), lower(), and upper().It has the `len()` function, which is a method commonly used in Python, and is also a method of objects.


*TIP: You might find it easier to understand methods as simple functions or actions.


The class is essentially a BlueprintHowever, I want to create... Object properties are defined as member variables, while actions are defined as methods.and can be used within the program.

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

I will declare and define it in this manner.

class car :
    car_name = '자동차'

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

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

For example, consider the "car" class. In this case, the "name" attribute is a member variable. Using a method: go() The function represents the action of a car moving forward.


*TIP: __init__() A method is a function. The method is automatically called immediately after the object is created. A constructor can clearly define what type of object a class represents, and it can initialize the object's member variables using parameters. To understand how constructors work, "Life Cycle"It would be helpful to understand this. There are many good resources available on this topic. Absolutely, definitely I recommend checking it out.


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

When creating and using a class, it typically has this structure. Declare variable names according to the class, and if the class has a constructor with parameters, include those parameters. If not, it can be omitted. Now, you can call the class's methods using these variable names to build the program logic.


The `__init__()` method and its inverse. __del__() This method is designed to release a class when its purpose has been fulfilled. When a class is declared and defined, it is allocated memory space. As programs are developed, numerous classes are used. In Java, for example, memory space is managed efficiently. Garbage CollectionThere's a mechanism in Python that automatically handles the destruction of a class when it's no longer needed. Therefore, you don't need to create a separate `__del__()` method.


An unusual method __add__() There is a method that allows for addition and multiplication with lists, similar to how it was possible with numbers. This method also enables addition with objects.

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 shown in the examples above Two objects (classes)This allows for the use of the same type of objects together. Similar to how "Genesis" and "K3" were defined separately, the class can be defined independently of the creator. While it is possible to directly access member variables, this is not recommended. Directly accessing member variables can make code longer and more difficult to maintain when using classes. One of the key reasons for using objects is Protecting data and internal structure (implementation)For "Encapsulation"However, this can lead to exposing the internal logic of the object to the outside world.


In addition, Class inheritance, the four main characteristics of objects (inheritance, abstraction, polymorphism, and encapsulation). There are many concepts to understand, and it would take a long time to cover them all. Therefore, I recommend continuously studying and seeking out helpful resources.



Review

I've been studying Python, which is becoming increasingly complex. In particular, I've been focusing on lists, tuples, dictionaries, and functions, which are all essential, and I can now create something with them. However, using classes elevates programming to a higher level. I still struggle to fully grasp the concept of object-oriented programming, but I feel a sense of accomplishment because I can now use it more effectively than before. I'm looking forward to studying networking and Linux, and I'm determined to work harder. 😄