Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Learning notes on python file operation

2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/03 Report--

# 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 ()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report