Skip to content

[Python] Tutorial(14) os, read and write the file

Last Updated on 2021-04-10 by Clay

Today my Python note will introduce how to use the package "os" and how to use read and write the file.

Especial we do some NLP research, Reading or Writing a file is a necessary skill.

Therefore, I will introduce the package os simply, and how to read and write the file.

If you want to read Python official tutorial, maybe you can refer:


os module

If we need to use this useful package, we need import this package.

import os


And then I will introduce the basic way to create folder, remove folder, how to get all the file name in the folder.

os.mkdir('./os_practice')


First, we need to use the above command to create a folder "0s_practice" in the folder of current script.

And then, if we want to remove a folder, we need just a simple command.

os.rmdir('./os_practice')


This way can remove the folder we create! Is it very easy?

Of course we don't delete this folder for now. The following, I note a simple way to traversal this folder.

Suppose we put three data in the folder we create, they called text01.txt, text02.txt, text03.txt

print(os.listdir('./os_practice/'))


Output:

['text01.txt', 'text02.txt', 'text03.txt']

Use function os.listdir() will print!

The functions in package os is more, so if you want to write a automated script is essential. You can query relevant functions according to requirements.


File read and write

The reading and writing of files is basically the same, the difference is what kind of mode we use when we open the file.
We always use "r", "w", "a" three modes.

"r" is reading this file, you can use function read().
"w" is writing in this file, you can use function write().
"a" is writing in this file again, continue the previous content, you can use function write().

Let's start with a simple demo: I just put three texts under os_practice, each of which contains different content, and now we read the text that printed three copies separately.

import os

text_list = os.listdir('./os_practice/')

for text in text_list:
    if text.endswith('.txt'):
        print('%s:' % text, open('os_practice/%s' % text, 'r', encoding='utf-8').read())


Output:

text01.txt: Today is a nice day!
text02.txt: Today is a bad day!
text03.txt: There is a typhoon!

First, import the os part at the begining. Next, we will use the os.listdir() to print all the files under the folder we create. and then we store them in variable text_list as a List data type.

Be careful, we use the endswith() function to confirm that the file ends with ".txt", and if so, we will do the processing.

As you can see, we opened a file, first enter the location of the file (that is, under os_practice), then, read the text using the pattern "r", and the encoding is set to UTF-8 (in Python, the encoding of all characters is it is UTF-8, if you don't set it under Windows, you will get an error.)

So, we will print the content of the text in a for-loop.

But, if we want to change content from a text?

Taking the first text as an example, our text is:

text01.txt:  Today is a nice day! 

Let's make a small change:

newContent = 'Are you sure today is a nice day?'

open('os_practice/text01.txt', 'w', encoding='utf-8').write(newContent)

print('text01.txt:',open('os_practice/text01.txt', 'r', encoding='utf-8').read())


Output:

text01.txt: Are you sure today is a nice day?

We can see that we saved the text in the newContent variable into text01.txt and replace it with the original content.

So if we don't want to replace the original content today, just want to add something behind it?

At this point, we need to change our pattern "w" to mode "a".

Let's take the example of text02:

text02.txt: Today is a bad day!

Then we made a small change to the program just now.

newContent = 'Is it really?'

open('os_practice/text02.txt', 'a', encoding='utf-8').write(newContent)

print('text02.txt:', open('os_practice/text02.txt', 'r', encoding='utf-8').read())


Output:

text02.txt:  Today is a bad day! Is it really?

How is it? Have we modified the original text, and have it been update directly?


This is the basic teaching of Python today.

Soon, the next note may be the last note of the basic tutorial - then I will record something more important and more practical.

I hope that I will like to write those things.


References


Read More

Leave a ReplyCancel reply

Exit mobile version