A, Python3 File (File) method
open () method
Python open () method is used to open a file and returns a file object in the file processing is required to use this function, if the file can not be opened, will throw OSError.
Note: Use the open () method must ensure that the closed file object that calls the close () method.
open () function accepts two parameters are used in the form of: a file name (file) and a mode (mode).
open(file, mode='r')
The complete syntax is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameter Description:
- file: Required, file path (relative or absolute path).
- mode: Optional, the file open mode
- buffering: a buffer
- encoding: utf8 general use
- errors: error level
- newline: distinguish line break
- closefd: Incoming file parameter types
- opener:
Common file objects:
file object using open function to create, the following table lists the file objects commonly used functions:
No. | Method and Description |
---|---|
1 | file.close () close the file. After closing the file can not read and write operations. |
2 | () file.flush internal refresh buffer files directly to the internal buffer of data written to the file immediately, rather than passively waiting for the output buffer written. |
3 | file.fileno () returns an integer file descriptor (file descriptor FD integer), it can be used in a method as read some of the underlying operating os module. |
4 | file.isatty () if the file is connected to a terminal device returns True, otherwise return False. |
5 | file.next () ** Python 3 in the File object does not support next () method. ** Returns the file the next line. |
6 | [File.read ( size]) Reads the specified number of bytes from the file, is not given, or if the reading of all negative. |
7 | [FILE.readline ( size]) to read the entire line, including "\ n" characters. |
8 | [file.readlines ( sizeint]) reads and returns a list of all the rows, if given sizeint> 0, the sum of the return line is approximately sizeint bytes, may be larger than the actual read value sizeint, because of the need to fill the buffer. |
9 | [file.seek (offset , The whence]) move the file to a specified location read pointer |
10 | file.tell () returns the current file position. |
11 | [file.truncate ( size]) the first line of the first character from the beginning of the file is truncated, file size characters, no size represents a cut from the current location; all the characters will be deleted after the cut, where the line breaks in the system represents a 2 Widnows character size. |
12 | file.write (str) the string to the file, it returns the written character length. |
13 | file.writelines (sequence) writes a list of strings to the file sequence, if necessary wrap will have their own line breaks added for each row. |
Exercise to get started:
The two merged into a txt file
Code section:
file_temp1 = {} #空字典用来存储从文件中读取的数据
file_temp2 = {}
def read_file():
file1 = open('file1.txt', 'r') #打开文件流
lines1 = file1.readlines() #返回列表
for line in lines1:
line = line.strip()
content = line.split(',')
file_temp1[content[0]] = content[1]
file1.close() #关闭文件流
with open('fiel2.txt', 'r') as file2: #无需手动关闭文件流
lines2 = file2.readlines()
for line in lines2:
line = line.strip()
content = line.split(',')
file_temp2[content[0]] = content[1]
def merge_file():
lines = []
header = "姓名\t 电话\t 邮箱\n"
lines.append(header) #插入到列表末尾、unshitf、浅拷贝
for key in file_temp1: #==for key in file_temp1.keys()
line = ''
if key in file_temp2:
line = line + '\t'.join([key, file_temp1[key], file_temp2[key]])
line += '\n'
else:
line = line + '\t'.join([key, file_temp1[key], ''])
line += '\n'
lines.append(line)
for key in file_temp2:
line = ''
if key not in file_temp1:
line += '\t'.join([key, '', file_temp2[key]])
line += '\n'
lines.append(line)
with open('file3.txt', 'w') as newfile: #创建并写入新文件
newfile.writelines(lines)
read_file()
merge_file()
Second, real simple student management system, student data stored in the document, support CRUD
Students read data from a file -> into memory, perform CRUD -> Save the file back (new file)
#面向对象、封装
class StudentSys:
#初始化
def __int__(self):
self.students = {} #字典存储学生信息
file = open('file4.txt', 'r')
lines = file.readlines() #一列表的形式返回数据
if len(lines) > 0: #不为空则赋值、要知道文件里面的内容才能具体处理
for key in lines:
line = key.strip().split()
self.students[line[0]] = line[1]
file.close()
#插入字典、判断是否存在
def addStu(self):
name = input("please input a student's name:\n")
stuID = input("please input a unique student's ID:\n").strip()
while True:
if stuID in self.students:
stuID = input("The student ID already exists, please enter again:\n").strip()
else:
break
self.students[stuID] = name
print("your operation is successful!")
#输入ID、存在则删除
def deleteStu(self):
stuID = input("please inout a student's ID:\n").strip()
while True:
if stuID not in self.students:
stuID = input("The student ID not exists, please enter again:\n").strip()
else:
break
del(self.students[stuID])
print("your operation is successful!")
def updateStu(self):
stuID = input("please inout a student's ID:\n").strip()
while True:
if stuID not in self.students:
stuID = input("The student ID not exists, please enter again:\n").strip()
else:
break
name = input("a student's name will be updated\n")
self.students[stuID] = name
print("your operation is successful!")
def queryStu(self):
stuID = input("please inout a student's ID:\n").str5ip()
if stuID not in self.students:
print("The student ID not exists!")
else:
print('find a student ID: ', stuID, 'name: ' + self.students[stuID])
def showAll(self):
print("total have", len(self.students), "students:")
for stuID in self.students:
print(stuID, '->', self.students[stuID])
#写入本地文件、最终一次性写入
def quitAndsave(self):
file = open('file5.txt', 'w')
lines = [] #空列表存储需要写入的信息
for key in self.students:
line = ''
line += '\t'.join([ str(key), self.students[key] ])
line += '\n'
lines.append(line)
file.writelines(lines)
file.close()
print("The program has been quit")
#实例化类
stuSys = StudentSys()
stuSys.__int__()
#主函数、try错误处理
while True:
print('''****welcome to student management system**********
1、add a new student
2、delete a student
3、update a student information
4、query a student information
5、show all students
6、quit the program''')
print("*" * 50)
try:
option = int(input("please input your options:\n"))
except Exception:
print("a error, please input a integer again!")
option = int(input("please input your options:\n"))
if option == 1:
stuSys.addStu()
elif option == 2:
stuSys.deleteStu()
elif option == 3:
stuSys.updateStu()
elif option == 4:
stuSys.queryStu()
elif option == 5:
stuSys.showAll()
elif option == 6:
stuSys.quitAndsave()
break
else:
print("a error, please input again!")