1.1 File Opening

  • Functions for creating, reading, updating, and deleting files
  • open
  • 4 modes to open files (R, A, W, X)
  • Processing mode: binary, text

1.2 File Reading

  • read
  • readline
  • close

Code practice

Open file ready to read data
f = open('Keyboard.txt',mode='rt', encoding='utf-8') 

#read() - Read data, all at once
# s = f.read()

#read(n) - Read n characters, starting from the current file read pointer
# s = f.read(10) 
# print(s)

# seek(n) - File read pointer moves back n bytes, starting at the start of the file by default
# f.seek(8) 
# s = f.read(5)
# print(s) 

# readlines() - Reads all the data and returns the list
# ss = f.readlines() 
# print(ss) 

#readline() - Reads 1 line
# s = f.readline()
# print(s) 
# s = f.readline()
# s = f.readline()
# s = f.readline()
# s = f.readline()
# s = f.readline()
Return an empty string if the end of the file is reached
# print(s+"<",len(s))  

# tell() - Current file pointer position
print(f.tell())

The file is read by the content, line by line
while True:
    s = f.readline()
    if s==' ':
        break
    print(s,end=' ')




print(f.tell())


# close file
f.close()
Copy the code

1.3 File Writing

  • Write to an existing file
  • Create a new file

The code example

Write files

"" mode - File opening mode r - read read W - write WRITE T - character operation encoding - character encoding, usually UTF-8" "
Open file ready to write characters
f = open('students. TXT',mode='w',encoding='utf-8') 

Write data
# f.rite ("Hello! )
# f.rite ("Hello! )
# f.rite ("Hello! )

# f.ritelines ("Hello! \n")
# f.ritelines ("Hello! \n")
# f.ritelines ("Hello! \n")

f.writelines(["Hello!."Hello!."Hello!])

# close file
f.close()   
Copy the code

Read and write

f = open('Keyboard.txt',mode='a',encoding='utf-8')

while True:
    s = input("Please enter :\n")
    if s==The '#':
        break 
    f.write(s)
    f.write("\n")  
    # refresh
    f.flush() 

# close file
f.close()
Copy the code

Byte operations

# byte manipulation
f = open("Students. TXT",mode='wb')  
f.write(b'hello')   # b - Converts strings into bytes
f.close()
Copy the code

1.4 Deleting a File

  • os.path.exists
  • rmdir

1.5 json file

import json
user={'name':'zhang'.'age':20} 

# dumps() - Converts Python objects into JSON strings
s = json.dumps(user)
print(s,type(s)) 

# loads() - convert JSON strings into Python objects
y = json.loads(s)
print(y['name'])


f=open('test. TXT'.'w',encoding='utf-8') 
# dump() - Python objects write json files
json.dump(user,f) 
f.close()

f=open('test. TXT'.'r',encoding='utf-8') 
# load() - Reads json files and converts them into Python objects
x = json.load(f) 
print(x,type(x)) 
f.close() 
Copy the code

1.6 the pickle

import pickle 

lst=["java"."python"."web"] 
f = open("Test pickle. TXT",mode='wb') 
# dump() - Serializes Python objects into bytes and saves them to binary files
pickle.dump(lst,f) 
f.close()

f = open("Test pickle. TXT",mode='rb') 
# load() - Read binaries to deserialize into Python objects
lst2 = pickle.load(f) 
print(lst2,type(lst2))   
f.close()
Copy the code

1.7 the IO

# sep - Separator, default is space
print("hello".123,sep=', ') 

user={'name':'zhang'.'age':20} 
print(user) 

Format the output
print('%(name)s %(age)d ' % user)

print('% S turns % D this year '% ('Ming'.18))  

print('% 10d'%12)  12 '#'

print('% 010.2 f' % 12.34567)  # '0000012.35'


#format Formats output
print('{} turns {} this year '.format('Ming'.18))  
print('{name} is {age} this year '.format(age=18,name='Ming'))  
print('{} turns {} this year '.format(18.'Ming'))  

print('{name} is {age} this year '.format(**user)) 

lst = ['lisi'.22]
print('{0[0]} this year {0[1]} is old '.format(lst))   # 0[0] equivalent to LST [0]


print('{num:*^#16x}'.format(num=199)) 

print('{:>#8b},{:>#8o},{:>#8x}'.format(9.9.9)) 

print("{0:.2f},{0:e},{0:.2%}".format(30.1415926525))
Copy the code

1.7 Actual Practice

There are many files in your computer that have been forgotten for a long time. Those big files take up disk space. Although hard disks are getting cheaper, it is not bad to use them, but it is fun to write a program to find these forgotten files

def get_big_file(path, filesize) :
    Param Path: :param filesize: :return: """
    pass
Copy the code

To accomplish this feature, two technical points need to be addressed:

  1. Walk through the folder and its subfolders to find all the file directories
  2. Gets the size of the file

Walk (os.walk) and os.path. getSize (os.path.getsize)