Basic Operation Phython basis --- files, integrated use

This article summarizes the file operation and use phython basis, learn together, and common progress



I. Introduction File Operations

  • What is the file
    Here Insert Picture Description
  • The role of file
  • Some storage is to store them, you can make the next time a program executed directly, without having to re-create a copy, saving time and effort

II. To read and write files

  • (1) write data (write)
  • Use write () to write data to a file can be done
  • Demo: Create a new file file_write_test.py, to write to the following code:
f = open('test.txt', 'w')
f.write('hello world, i am here!')
f.close()
运行之后会在file_write_test.py文件所在的路径中创建一个文件test.txt,其中数据如下:

Here Insert Picture Description

  • Note: If the file does not exist then create, if there is then emptied first, then write the data.

  • (2) read data (Read)
  • Use read (num) can read data from a file, NUM represents the length of the data read from the file (in bytes), if no incoming num, it means that all the data file is read
  • Demo: Create a new file file_read_test.py, to write to the following code:
f = open('test.txt', 'r')
content = f.read(5)  # 最多读取5个数据
print(content)

print("-"*30)  # 分割线,用来测试

content = f.read()  # 从上次读取的位置继续读取剩下的所有的数据
print(content)

f.close()  # 关闭文件,这个可以是个好习惯哦
  • 运行结果:
hello
------------------------------
 world, i am here!
注意:

如果用open打开文件时,如果使用的"r",那么可以省略,即只写 open('test.txt')

  • (3) read data (the readlines)
  • When read as no argument, the readlines entire contents of file can be read in one time-line manner, and returns a list, where each data row as an element
#coding=utf-8

f = open('test.txt', 'r')
content = f.readlines()
print(type(content))

i=1
for temp in content:
    print("%d:%s" % (i, temp))
    i += 1

f.close()

Here Insert Picture Description


  • (4) read data (the readline)
#coding=utf-8
f = open('test.txt', 'r')

content = f.readline()
print("1:%s" % content)

content = f.readline()
print("2:%s" % content)

f.close()

Here Insert Picture Description


Think about it: If a file is large, such as 5G, should imagine how to read the data file into memory and then deal with it?

Here Insert Picture Description


Make a backup file: Three applications 1.

  • Task Description : Enter the name of the file, then the program automatically back up files
    Here Insert Picture Description
    Here Insert Picture Description
# 提示输入文件
oldFileName = input("请输入要拷贝的文件名字:")

# 以读的方式打开文件
oldFile = open(oldFileName,'rb')

# 提取文件的后缀
fileFlagNum = oldFileName.rfind('.')
if fileFlagNum > 0:
    fileFlag = oldFileName[fileFlagNum:]

# 组织新的文件名字
newFileName = oldFileName[:fileFlagNum] + '[复件]' + fileFlag

# 创建新文件
newFile = open(newFileName, 'wb')

# 把旧文件中的数据,一行一行的进行复制到新文件中
for lineContent in oldFile.readlines():
    newFile.write(lineContent)

# 关闭文件
oldFile.close()
newFile.close()

Related operations IV. File

Sometimes, you need to file rename, delete some operations, python os module has such a function

  • Rename the file
  • os module rename () can be done to the file rename operation
rename(需要修改的文件名, 新的文件名)
import os
os.rename("毕业论文.txt", "毕业论文-最终版.txt")
  • Delete Files
  • os module remove () to complete the deletion of files
remove(待删除的文件名)
import os
os.remove("毕业论文.txt")
  • Create a folder
import os
os.mkdir("张三")
  • Get the current directory
import os
os.getcwd()
  • Get a directory listing
import os
os.listdir("./")
  • Delete the folder
import os
os.rmdir("张三")

V. Application 2: Batch modify the file name

  • Run the demo process
  • Before running the program

Run the demo process

  • After running the program

Here Insert Picture Description

  • Reference Code
#coding=utf-8
# 批量在文件名前加前缀
import os

funFlag = 1 # 1表示添加标志  2表示删除标志
folderName = './renameDir/'

# 获取指定路径的所有文件名字
dirList = os.listdir(folderName)

# 遍历输出所有文件名字
for name in dirList:
    print name

    if funFlag == 1:
        newName = '[东哥出品]-' + name
    elif funFlag == 2:
        num = len('[东哥出品]-')
        newName = name[num:]
    print newName

    os.rename(folderName+name, folderName+newName)


  • Thank you for your reading. May we make progress together
Published 50 original articles · won praise 354 · views 50000 +

Guess you like

Origin blog.csdn.net/weixin_45393094/article/details/105269751