Study from Python Reading and writing Hour9 files

Study from Python Hour9: Reading and writing files

Learning materials

Past posts

environment

Reading and writing files is the same as a text editor! This is important

  1. Open the file
  2. Read and write
  3. Close the file
  1. Specify the mode (reading (r), appending (a), overwriting (w)) when opening or opening with the open function.
  2. Read and write using the read method etc.
  3. Close with the close method

Read a text file

Try to open 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')#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

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

>>> 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

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

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

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

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

For Quotations / Lightning Talk

Recommended Posts

Study from Python Reading and writing Hour9 files
Reading and writing JSON files with Python
Reading and writing CSV and JSON files in Python
Reading and writing fits files with Python (memo)
Reading and writing csv files
Study from Python Hour4: Object-oriented ②
Study from Python Hour3: Functions
Study from Python Hour4: Object-oriented ①
[Introduction for beginners] Reading and writing Python CSV files
Read and use Python files from Python
Study from Python Hour2: Control statements
Python CSV file reading and writing
Reading and writing NetCDF with Python
Reading and writing CSV with Python
Reading and writing text in Python
uproot: Python / Numpy based library for reading and writing ROOT files
Study from Python Hour7: How to use classes
Reading from text files and SQLite in Python (+ Pandas), R, Julia (+ DataFrames)
Case sensitive when reading and writing INI files
[Python] Reading CSV files
Example of reading and writing CSV with Python
Character code for reading and writing csv files with python ~ windows environment ver ~
Study from the beginning of Python Hour1: Hello World
Study from the beginning of Python Hour8: Using packages
Get files from Linux using paramiko and scp [Python]
Reading .txt files with Python
Notes on reading and writing float32 TIFF images in python
Manipulate files and folders in Python
About Python, from and import, as
Export and output files in Python
Extract strings from files in Python
Reading and writing Files from notebook on Watson Studio to IBM Cloud Object Storage (ICOS)-using project-lib-
From Python to using MeCab (and CaboCha)
Play audio files from Python with interrupts
[Python] Reading and writing photo location information tags (JPG file GPS Exif)
Decrypt files encrypted with openssl from python with openssl
(Python) HTML reading and regular expression notes
Porting and modifying doublet-solver from python2 to python3.
[Easy Python] Reading Excel files with openpyxl
Get options in Python from both JSON files and command line arguments
Read and write JSON files in Python
[Easy Python] Reading Excel files with pandas
Firebase: Use Cloud Firestore and Cloud Storage from Python
[Kaggle] From data reading to preprocessing and encoding
[Python] How to read data from CIFAR-10 and CIFAR-100
[Python] Find coordinates from two angles and distance
Load and execute command from yml in python
Drag and drop local files with Selenium (Python)
PHP and Python integration from scratch on Laravel
Split files when writing vim plugin in python
Download and import files with Splunk external python
PDF files and sites useful for learning Python 3
Comparison of R and Python writing (Euclidean algorithm)
Generate and output plantuml object diagram from Python object
Python study note_002
Python study notes _000
Python study notes_006
Python study note_004
A python client application that downloads and deletes files from S3 by specifying a bucket
sql from python
Basic Python writing