3-1-5-17. Reading and Writing Files

and we routinely create, move,

manipulate, and read these files in our daily digital lives.

All the data we’ve used so far has been defined inside

the Python script or raw input from the user during execution of the script.

Next, we’re going to massively increase the variety of what we can achieve in

our Python programming by introducing how to read and write files in Python.

This will allow us to interact with and process

larger amounts of information from many more sources.

All kinds of files have a similar structure on a computer.

There are strings of characters that encode some information.

The specific file format,

often indicated by the extension of the file name such as.py,

TXT, HTM, CSV, and many more,

will indicate how those characters are organized.

The characters in a file are interpreted by

the various programs we use to interact with them.

For example, an image editing program will interpret

the information of a digital photograph file and display the image.

If we then edit the image in the program,

were using this program to make changes to the characters in the file.

In Python, we can read those file characters directly.

The experience will seem quite different from opening a file in a desktop application.

Opening files in Python gives us

a common programmatic interface to all kinds of

files without the need for a graphical user interface,

which means we can automate tasks involving files with Python programs.

정말 유용한 프로그램이 되기 위해서는

실제 데이터와 상호 작용해야 합니다.

이미지, 웹 페이지 및 데이터베이스는 모두 파일의 예입니다.

우리는 일상적으로 만들고, 움직이고,

일상적인 디지털 생활에서 이러한 파일을 조작하고 읽습니다.

지금까지 사용한 모든 데이터는 내부에 정의되어 있습니다.

Python 스크립트 또는 스크립트 실행 중 사용자의 원시 입력.

다음으로, 우리가 달성할 수 있는 것의 다양성을 대폭 늘릴 것입니다

Python에서 파일을 읽고 쓰는 방법을 소개하여 Python 프로그래밍을 소개합니다.

이를 통해 우리는 상호 작용하고 처리할 수 있습니다.

더 많은 소스에서 더 많은 양의 정보를 얻을 수 있습니다.

모든 종류의 파일은 컴퓨터에서 유사한 구조를 가지고 있습니다.

일부 정보를 인코딩하는 문자열이 있습니다.

특정 파일 형식,

종종 .py와 같은 파일 이름의 확장자로 표시됩니다.

TXT, HTM, CSV 등

해당 문자가 구성되는 방식을 나타냅니다.

파일의 문자는 다음과 같이 해석됩니다.

우리가 그들과 상호 작용하기 위해 사용하는 다양한 프로그램.

예를 들어 이미지 편집 프로그램은

디지털 사진 파일의 정보를 표시하고 이미지를 표시합니다.

그런 다음 프로그램에서 이미지를 편집하면

이 프로그램을 사용하여 파일의 문자를 변경했습니다.

Python에서는 해당 파일 문자를 직접 읽을 수 있습니다.

경험은 데스크탑 응용 프로그램에서 파일을 여는 것과 상당히 다르게 보일 것입니다.

Python에서 파일을 열면

모든 종류의 공통 프로그래밍 인터페이스

그래픽 사용자 인터페이스가 필요 없는 파일,

이는 Python 프로그램으로 파일과 관련된 작업을 자동화할 수 있음을 의미합니다.

파일을 열 수 있는 다양한 모드에 대한 자세한 정보.

쓰기 모드에 있고 이 파일에 있는 내용을 삭제하고 싶지 않기 때문에

다른 것을 사용합시다.

파일이 존재하지 않는 경우,

파이썬이 당신을 위해 그것을 만들 것입니다.

이제 다음과 같이 파일에 쓸 수 있습니다.

우리가 끝나면 좋은 시민처럼 닫을 것입니다.

여기에서 Python이 “Hello World!”라는 텍스트가 포함된 다른 파일을 생성했음을 알 수 있습니다.

Reading and Writing Files

To follow along with the example above, create a new file in Atom, copy the following text into it, and save it as some_file.txt!

Hello!!

You've read the contents of this file!

Here’s how we read and write files in Python.

Reading a File

f = open('my_path/my_file.txt', 'r')
file_data = f.read()
f.close()
  1. First open the file using the built-in function, open. This requires a string that shows the path to the file. The open function returns a file object, which is a Python object through which Python interacts with the file itself. Here, we assign this object to the variable f.
  2. There are optional parameters you can specify in the open function. One is the mode in which we open the file. Here, we use r or read only. This is actually the default value for the mode argument.
  3. Use the read method to access the contents from the file object. This read method takes the text contained in a file and puts it into a string. Here, we assign the string returned from this method into the variable file_data.
  4. When finished with the file, use the close method to free up any system resources taken up by the file.

Writing to a File

f = open('my_path/my_file.txt', 'w')
f.write("Hello there!")
f.close()
  1. Open the file in writing (‘w’) mode. If the file does not exist, Python will create it for you. If you open an existing file in writing mode, any content that it had contained previously will be deleted. If you’re interested in adding to an existing file, without deleting its content, you should use the append (‘a’) mode instead of write.
  2. Use the write method to add text to the file.
  3. Close the file when finished.

Too Many Open Files

Run the following script in Python to see what happens when you open too many files without closing them!

files = []
for i in range(10000):
    files.append(open('some_file.txt', 'r'))
    print(i)

With

Python provides a special syntax that auto-closes a file for you once you’re finished using it.

with open('my_path/my_file.txt', 'r') as f:
    file_data = f.read()

This with keyword allows you to open a file, do operations on it, and automatically close it after the indented code is executed, in this case, reading from the file. Now, we don’t have to call f.close()! You can only access the file object, f, within this indented block.

%d