Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

Learning notes on python file operation

Shulou Source: shulou.com Published: 2022-06-03 05:23:34 10月23日 Update

# File operations:

Read:

F = open ("/ Users/zhouhaijun/python/01.py", "r")

X = f.read ()

Print x

Write:

F = open ("/ Users/zhouhaijun/python/file_01.py", "wb")

F.write ("ok")

F.close ()

Read:

F = open ("/ Users/zhouhaijun/python/file_01", "r")

Text = f.read () # text = f.read

Print text

Read one line:

Print f.readline () # read by line

The next function is to copy the file, reading and writing fifty characters at a time. The first parameter is the source document name, and the second parameter is the new file name

Def copyFile (oldfile, newfile):

F1 = open (oldfile, "r")

F2 = open (newfile, "w")

While 1:

Text = f1.read (50)

If text = "":

Break

F2.write (text)

F1.close ()

F2.close ()

Return

The next example is a line processor, where the function filterFile copies a file and sets the old

Lines in the file that do not begin with "#" are written to the new file:

Def fileterFile (old, new):

Sfile = open (old, "r")

Dfile = open (new, "w")

While 1:

Text = sfile.readline ()

If text = "":

Break

Elif:

Text [0] = "#":

Continue

Else:

Dfile.write (text)

Sfile.close ()

Dfile.close ()

Tags: File next function parameter copy one line example at the same time character beginning file name program processing note learning Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi Huawei macOS Shulou Tech Info Apple