python Read Write Delete Copy File Operation Method Detailed Example Summary

  • 2021-10-24 23:13:32
  • OfStack

python Read File Operation

1. read 3 different ways


f = open('hello.txt') #'hello.txt' Refers to the name of the file 
while True:
  text = f.readline()  # Read which file pointer points to 1 Line contents, and then the pointer moves down 
  if text:
    print(text)
  else: # When the text comes to the end, 1 OK, 3 Empty string 
    print(len(text))
    break
f.close() # Close the file and run 1 Under 

f = open("hello.txt")
line_list = f.readlines() #1 Secondary reading, expressed in the form of a list 
print(type(line_list))
for line in line_list:
  print(line)
f.close()

f = open("hello.txt")
s = f.read() #1 Read all the contents in a secondary way and return them in the form of strings 
print(type(s))

for line in s:
  print(line,end=' ')

f.close()

python Write File Operation

2. Two common basic ways of writer


f = open('poet.txt','w',encoding='utf-8') # Open a file in write mode 
f.write(' Hello, python') # Write content 
print(" Write complete, run! ")
f.close()

f = open("poet.txt",'a+')
print(f.read())
fruits = ['appple\n','banana\n','orange\n','watermelon\n']
f.writelines(fruits)
print(' Write successful ')
f.close()

python Delete File Action

3. delete Delete


import os,os.path
if os.path.exists("sd.txt"):
  os.remove("sd.txt")  
  print(" Delete succeeded ")
else:
  print(' File does not exist ')

Delete the same file format of the same file


import os

files = os.listdir('.') # Lists all files and subdirectories in the specified directory 
for filename in files:
  point_index = filename.find(".") # Get '. 'Indexed position in file 
  if filename[point_index + 1:] == "txt": # Determines whether the extension of the current file is 'txt ' 
    os.remove(filename)  # Delete a file 

python Copy File Operation

4. copy replication

Method 1


srcFile = open("a.txt") # Source file 
destFile = open("a_copy.txt",'w') # Object file 
destFile.write(srcFile.read()) # Writes the contents read from the source file to the destination file 
destFile.close()
srcFile.close()
print(' Copy complete ')

The second usage module


with open("a.txt") as src,open("a_copy.txt",'w') as dest:
  dest.write(src.read())
print(' The copy was successful! ')

Worse, please see the relevant links below for a detailed example of python reading, writing, deleting and copying files


Related articles: