Training notes 20,190,731

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/weixin_43895902/article/details/97947322

Article Directory

file

  • The file operation
    is data on the disk read and write operations - derived technology IO operations
    read and write operations: read, write

Q: What is the IO operation?
The I - InputStream input stream of bytes
O - OutputStream output stream of bytes

  • open a file
#创建一个demo.txt
file_name='demo.txt'
file_obj=open(file_name)

#r表示的是原始字符串,以下为绝对路径写法规范
file_name = r'C:\Users\lilichao\Desktop\hello.txt'
  • open()函数
    open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

mode has the following values:
Here Insert Picture Description

  • Read the contents of the file
file_name='demo.txt'

#第一步:打开文件
file_obj=open(file_name)

#第二步,通过read,将磁盘数据写到服务器/控制台
content=file_obj.read()
print(content)

#第三步,close关闭文件
file_obj.close()

Q: If the IO operations, IO does not close, what happens?
A: If you do not close the IO, will definitely lead to data leakage, data is not secure

Q: jdbc explanation
A: Close four times: collection, statement, resultset, class.forname ... Open four times :( written in Java so bad)

How to solve?
University: Using DBUtils packaging
companies: C3po, JNDI, datasource-Mybatis
use resources more resources IO operation certainly will not leak, the server reads speed, high performance, security

Solving methods must frequently close in Python inside
use with ... as ...

with open(file_name) as file_obj:
	print(file_obj.read)

This is done by with ... as ... you can automatically shut down after the program execution is complete IO operation safe and efficient.

What program can not read the files belong?

  1. Program during reading, certainly can not find the case - FindNotFileexception
  2. Variable not assigned - IO operations because there are many uncontrollable factors
try:
	file_obj=open(file_name)
	content=file_obj.read()
	print(content)
except FindNotFoundError:
	#肯定有文件读取不到的时候,需要抛异常,捕获异常,让程序变得更加安全
	print('出错了')
  • File read processing in
    Python or other languages are machine code, is not very sensitive to the Chinese, you need to manually handle

Call open () to open a file, the file can be divided into two types
one of plain text files (such as using utf-8 encoded text file written)
one of binary files (pictures, mp3, ppt, etc. These files )

Garbled Cause / Chinese does not recognize the emergence of: open () to open the file, the default is a text file open, but open () default encoding encoding to None, so when dealing with text files, it is necessary to specify the encoding of the file

#创建一个中文文档
file_name='demo2.txt'
try:
	file_obj=open(file_name,encoding='utf-8')#转码
	content=file_obj.read()
	print(content)
except FindNotFoundError:
	print('文件不存在')

-read function can file all the documents inside a full reading, when there are huge amounts of data, read function can not be used, if forced to use read read huge amounts of data, the structure of what will happen:
1. Data blockage occurs
2. Data leaks
3. complete loss of data, data atomicity violation things, ionic, etc.

read () may receive a size as a parameter, which specifies the number of characters to read
default value is -1, it reads all the characters in the file,
you can specify a value for the size, so that read () willReads a specified number of characters, and each time is read from the last read position to start reading
If the size is less than the number of characters, all remaining will be read, if the file has been read to the last, and would return '' empty string
content = file_obj.read (-1)

  • the readline ()
    of this method are used to read line by line, it will read one time to return the package to a list of
    content = file_obj.readline ()
file_name = 'demo.txt'

with open(file_name , encoding='utf-8') as file_obj:
	print(file_obj,read())
	r=file_obj.readline()
	print(r)
	#将数据通过readline()返回一个列表,也可以将数据保存到列表
	#pprint.pprint(r[0])
	#pprint.pprint(r[1])
	for t in file_obj:#遍历数据快
		print(t)
  • Read large files
# 读取大文件的方式
file_name = 'demo.txt'

try:
    with open(file_name,encoding='utf-8') as file_obj:
        # 定义一个变量,来保存文件的内容
        file_content = ''
        # 定义一个变量,来指定每次读取的大小
        chunk = 100
        # 创建一个循环来读取文件内容
        while True:
            # 读取chunk大小的内容
            content = file_obj.read(chunk)

            # 检查是否读取到了内容
            if not content:
                # 内容读取完毕,退出循环
                break

            # 输出内容
            # print(content,end='')
            file_content += content

except FileNotFoundError :
    print(f'{file_name} 这个文件不存在!')


print(file_content)

Write to the file

Using the open () must be specified to open the file to do the operation (read, write, append) when you open the file
if you do not specify the type of operation, the default file is read, and when reading the file can not be written to the file

mode meaning
r It represents read-only
w Representation is writable, use w to write to the file, the file will be created if the file does not exist, it will truncate the file if the file exists, truncate the file means that all delete the original file
a Represents additional content, will create the file if the file does not exist, if the file exists it will be appended to the file contents
x To a new file, if the file does not exist it is created, then there is an error
+ Increasing function operator
r+ Can be read but also write, the file does not exist error
w+ Open a file for reading and writing. If the file already exists then open the file and start editing from the beginning, that is, the original content will be deleted. If the file does not exist, create a new file.
a+ Open a file for reading and writing. If the file already exists, the file pointer will be placed at the end of the file. It would append mode when the file is opened. If the file does not exist, create a new file for reading and writing.
with open(file_name , 'x' , encoding='utf-8') as file_obj:
    # write()来向文件中写入内容,
    # 如果操作的是一个文本文件的话,则write()需要传递一个字符串作为参数
    # 该方法会可以分多次向文件中写入内容
    # 写入完成以后,该方法会返回写入的字符的个数
    file_obj.write('aaa\n')
    file_obj.write('bbb\n')
    file_obj.write('ccc\n')
    r = file_obj.write(str(123)+'123123\n')
    r = file_obj.write('今天天气真不错')
    print(r)

NumPy

One kind of a file-based operating scientific computing and multi-dimensional arrays like / Function

Guess you like

Origin blog.csdn.net/weixin_43895902/article/details/97947322