Study from Python Hour9: Reading and writing files
- When I tried to do something with Python, I first searched for a sample script and somehow executed it.
- 7 hours I want to hit REST API with automatic execution, check the result, and even operate the VM
- If you think about it, it will be 10 times over 7 hours.
- This time, read and write files. It seems that it will be possible to handle CSV and JSON files
Learning materials
- Learn the basics in just one day! A super introduction to Python
- https://a.r10.to/hbHMiv
Past posts
environment
- Windows
- Python Ver3 series
Reading and writing files is the same as a text editor! This is important
- This is the same for any programming language, but reading and writing files is as follows
- Open the file
- Read and write
- Close the file
- Specify the mode (reading (r), appending (a), overwriting (w)) when opening or opening with the open function.
- Read and write using the read method etc.
- Close with the close method
Read a text file
- Read a text file
- When you normally use a text editor on your computer, opening a file with the "Open" menu will display the contents of the file on the screen, but in Python you can open it with the open function.
- You will get a "file object" when you open it with the open function.
Try to open the file
- Take a look at the process in interactive mode
C:\script>python
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> fin = open('aaa.txt', 'r')#aaa with open function.Open txt in read mode. fin is a file object
>>> print(fin)
<_io.TextIOWrapper name='aaa.txt' mode='r' encoding='cp932'>
>>>
>>> #When you print an object, the file name and mode read(r)Is displayed. * The contents are not displayed
- Reads a file object called fin.
Try to read the contents of the file
C:\script>python
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> fin = open('aaa.txt', 'r')
>>> print(fin)
<_io.TextIOWrapper name='aaa.txt' mode='r' encoding='cp932'>
>>>
>>> text = fin.read() #Read the entire contents of the file with the read method
>>> print(text)
aaa
bbb
ccc
>>>
Close when finished
C:\script>python
Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:37:50) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> fin = open('aaa.txt', 'r')
>>> print(fin)
<_io.TextIOWrapper name='aaa.txt' mode='r' encoding='cp932'>
>>>
>>> text = fin.read()
>>> print(text)
aaa
bbb
ccc
>>>fin.close() #If you do not close it, it will remain using OS resources
>>>
Add to file
- Try adding to the file in the same way.
>>> fadd = open('aaa.txt', 'a') #Open in append mode
>>> fadd.write('write add text\n') #Add text
>>> fadd.close() #Close file
>>>
>>>
>>>
>>> fin = open('aaa.txt', 'r') #Take a look at the contents of the file as you did at the beginning
>>> text = fin.read()
>>> print(text)
aaa
bbb
ccc
write add text #You can see that it was added
>>>
Use user input
- Arguments when the program is executed on the command line, prompting the user for input in the middle of the program, and using the values.
Input by argument
C:\script>test50_print_arg.py hogeo hoge2 #If you pass two arguments
['C:\\script\\test50_print_arg.py', 'hogeo', 'hoge2'] #Can be used during the program
C:\script>
Contents of the executed script
import sys
print(sys.argv) #It is a program that only outputs arguments
Read the file with command line arguments
- Generally, writing variable things such as file names directly in the code is not versatile, so let's pass it as an argument.
Script to read the file specified by the argument
import sys
fin = open(sys.arg[1], 'r')
print(fin.read())
fin.close()
Execution result
C:\script>test51_print_argfiles.py aaa.txt
aaa.txt
aaa
bbb
cccwrite add text
- In this case, if there is an invalid argument, the processing will stop, so let's handle the error in the program that is supposed to be passed as an argument.
- Let's put in the general processing of argument checking.
Script to read the file specified by the argument (with error handling)
import sys
if len(sys.argv) < 2: #One (less than) error handling argument
print ('Error!! Please input filename')
exit()
FILE_NAME = sys.argv[1]
fin = open(FILE_NAME, 'r')
print(fin.read())
fin.close()
Execution result
C:\script>test52_print_argfiles2 ー.py
Error!! Please input filename #It's better than Python's inorganic errors.
C:\script>test52_print_argfiles2 ー.py aaa.txt
aaa
bbb
C:\script>
Prompt for input in the middle of the program
- If you use the input function, the program will prompt you for input.
- The return value of the input function can be treated as a character string.
Enter the file name and display the contents of the file (Please save in UTF-8 in Japanese)
print('Phtyon Start!!')
file_name = input('Please enter the file name. input fine name= ')
fin = open(file_name, 'r')
print(fin.read())
fin.close()
Execution result
C:\script>test53_input.py
Phtyon Start!!
Please enter the file name. input fine name= aaa.txt
aaa
bbb
C:\script>
This summary
- I've always been stuck with file IO in each language, but it was easy to handle. The program is the same as a normal text editor!
- I think it's more common to read and process than to write, so I hope I can do this.
- If you take a quick look around here, it feels like the first step in mastering it.
For Quotations / Lightning Talk
- A program with a high degree of freedom that has arguments and user input requires error handling. difficult