In any programming language, file operation is the most basic function. Python is very simple and direct in file operation. It has built-in functions for reading and writing files, which can be called directly in the program. In reading and writing files, there are various problems, such as whether the file exists, whether it has permissions, and how to catch reading and writing exceptions, which are very simple in Python.
read file
Suppose we already have the test.txt file in the project directory:
file = open('test.txt','r')
print(file.read())
file.close()
exception handling
try:
file = open('test.txt','r')
print(file.read())
except IOError as ierr:
print('Read file error: ' + str(ierr))
finally:
if file:
file.close()
try-except-finally can handle file open exceptions, but it's a bit cumbersome. Python can use with open() to close files automatically.
try:
with open('test.txt','r') as file_new:
print(file_new.readline())
except IOError as ierr:
print("read file error: " + str(ierr))
write file
try:
with open('test1.txt','w') as file_write:
file_write.write('Hello World!')
except IOError as ierr:
print("Write file error: " + str(ierr))
If the file does not exist, a new file will be created, and if it already exists, the current file will be overwritten.
Operation file directory
import os
print(os.path.abspath('.'))
new_dir = os.path.join(os.path.abspath('.'),'testdir')
print(new_dir)
os.mkdir(new_dir)
Handle with JSON format
Keywords: import JSON, json.dumps, json.loads
import json
json_obj = dict(name='Bob',hobby="basketball")
s = json.dumps(json_obj)
print(s)
json_str='{"order": 12345678,"sold-to": "sd123345"}'
d = json.loads(json_str)
print(d)
summary
Python file processing is relatively simple, JSON format processing is powerful, and more general and practical.
Appendix - source code
import os
print('File operation - exception handling')
try:
file = open('test.txt','r')
print(file.read())
except IOError as ierr:
print('Read file error: ' + str(ierr))
finally:
if file:
file.close()
print('File operation - Use with')
try:
with open('test.txt','r') as file_new:
print(file_new.readline())
except IOError as ierr:
print("read file error: " + str(ierr))
print('File operation - write file')
try:
with open('test1.txt','w') as file_write:
file_write.write('Hello World!')
except IOError as ierr:
print("Write file error: " + str(ierr))
try:
with open('test1.txt','r') as file_write:
print(file_write.readline())
except IOError as ierr:
print("Write file error: " + str(ierr))
print('Operation file directory')
print(os.path.abspath('.'))
new_dir = os.path.join(os.path.abspath('.'),'testdir')
print(new_dir)
os.mkdir(new_dir)
print("JSON Format processing")
import json
json_obj = dict(name='Bob',hobby="basketball")
s = json.dumps(json_obj)
print(s)
json_str='{"order": 12345678,"sold-to": "sd123345"}'
d = json.loads(json_str)
print(d)