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

How does python operate on files

2025-04-09 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article will explain in detail how to manipulate files in python. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

First look at the input file handle in pycharm, how to display its definition

F = open ('student_msg', encoding='utf-8', mode='a+') # Open a file and assign a value to f

The print (type (f), f) # f file handle belongs to a class called, which is also an iterable object. (io-- > input and out)

Print (dir (f)) # prints all the properties and methods of this class

['_ CHUNK_SIZE', 'class',' del', 'delattr',' dict', 'dir',' doc', 'enter',' eq', 'exit',' format', 'ge',' getattribute', 'getstate',' gt', 'hash',' init', 'init_subclass',' iter', 'le',' lt', 'ne',' new', 'next',' reduce' 'reduce_ex', 'repr',' setattr', 'sizeof',' str', 'subclasshook',' _ checkClosed','_ checkReadable','_ checkSeekable','_ checkWritable','_ finalizing', 'buffer',' close', 'closed',' detach', 'encoding',' errors', 'fileno',' flush', 'isatty',' line_buffering', 'mode',' name', 'newlines' 'read', 'readable',' readline', 'readlines',' reconfigure', 'seek',' seekable', 'tell',' truncate', 'writable',' write', 'write_through',' writelines']

Print (f.dict) # f the attribute {'mode':''} in the instantiated object

Its interpretation and definition by source code

''

=

Character Meaning

'r 'open for reading (default) defaults to read-only' w 'open for writing. Truncating the file first first truncates (deletes all the files)' x 'create a new file and open it for writing'a' open for writing, appending to the end of the file if it exists append mode' b' binary mode binary mode When opening a picture or non-text format, t 'text mode (default) reads the text' + 'open a disk file for updating (reading and writing) is readable and writable by default.

''

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

The operation of the file is still used frequently, and these methods are easy to be confused. In order to avoid future deviation, I have sorted out several commonly used methods.

One,. Readline () and .readlines () are intended to browse and find out what mode is used for the content in the file. Let's first look at the results of execution in six ways.

In the register file, take a look at the results returned by each of the six methods

"'

These are the contents of the file.

Dumingjun

Mickle | male

"'

Mode='r'

With open ('register', encoding='utf-8', mode='r') as f:

Print (f.readline ())

Print (f.readlines ())

Running result: (there is no change in the file)

''

These are the contents of the file.

['dumingjun\ nails,' mickle | male']

''

Mode='r+'

With open ('register', encoding='utf-8', mode='r+') as f:

Print (f.readline ())

Print (f.readlines ())

Running result: (there is no change in the file)

''

These are the contents of the file # read a line first

['dumingjun\ nlegs,' mickle | male'] # then execute down, putting each line in the container of the list as a string with a newline character\ n

''

Mode='w'

With open ('register', encoding='utf-8', mode='w') as f:

Print (f.readline ())

Print (f.readlines ())

Run result: (there is no content in the file)

''

Traceback (most recent call last):

Print (f.readline ())

Io.UnsupportedOperation: not readable # error reason: the'w' mode cannot be read. As long as you see the 'wicked', empty the files first.

''

Mode='w+'

With open ('register', encoding='utf-8', mode='w+') as f:

Print (f.readline ())

Print (f.readlines ())

Run result: (the content of the file is empty)

''

Clear it first, and then execute f.readline (), which returns an empty character because it is empty.

[] # then execute f.readlines () to return an empty list

''

Mode='a'

With open ('register', encoding='utf-8', mode='a') as f:

Print (f.readline ())

Print (f.readlines ())

Running result: (the content of the file remains unchanged)

''

Traceback (most recent call last):

Print (f.readline ())

Io.UnsupportedOperation: not readable # error reason,'a' mode can only be add, added, not readable, because the time mark is automatically placed at the end of the file when it goes into'a' mode.

''

Mode='a+'

With open ('register', encoding='utf-8', mode='a+') as f:

Print (f.readline ())

Print (f.readlines ())

Running result: (the content of the file remains unchanged)

''

Because the cursor is placed at the end, the read content is empty

[] # similarly, redlines () returns an empty list.

''

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

forty

forty-one

forty-two

forty-three

forty-four

forty-five

forty-six

forty-seven

forty-eight

forty-nine

fifty

fifty-one

fifty-two

fifty-three

fifty-four

fifty-five

fifty-six

fifty-seven

fifty-eight

fifty-nine

sixty

sixty-one

sixty-two

sixty-three

sixty-four

sixty-five

sixty-six

sixty-seven

sixty-eight

sixty-nine

seventy

seventy-one

seventy-two

seventy-three

seventy-four

seventy-five

seventy-six

seventy-seven

seventy-eight

seventy-nine

eighty

eighty-one

eighty-two

eighty-three

eighty-four

eighty-five

eighty-six

eighty-seven

eighty-eight

eighty-nine

ninety

ninety-one

ninety-two

The contents of the above code are displayed on the picture:

Write the picture description here.

Write the picture description here.

Write the picture description here.

Summary

Write the picture description here.

Read and find relevant content, using only'r' or 'ritual' mode.

Now to create a new file and add content, first take a look at the results of the five methods

''

Create a file named 'msg' and write the following:

"Duminjun is swimming\ nChicken tonight."

''

R mode does not need to try, r can only read, try r + mode with open ('msg9', encoding='utf-8', mode='r') as f:f.write (' Duminjun is swimming\ neat chicken tonight') run result:

''

Traceback (most recent call last):

With open ('msg', encoding='utf-8', mode='r+') as f:

FileNotFoundError: [Errno 2] No such file or directory: 'msg' # does not have a file named' msg', which proves that r + mode cannot add files

''

A mode with open ('msg', encoding='utf-8', mode='a') as f:f.write (' Duminjun is swimming\ neat chicken tonight')

#

The result of the run (the file of 'msg' has been added to this directory, and the open file shows the following:

''

Duminjun is swimming # a mode can create files and write to

Eat chicken tonight

''

A + mode with open ('msg', encoding='utf-8', mode='a+') as f:f.write (' Duminjun is swimming\ neat chicken tonight') result: the result is the same as the above an operation result: W mode with open ('msg', encoding='utf-8', mode='w') as f:f.write (' Duminjun is swimming\ n eat chicken tonight') result: same as a mode w + mode with open ('msg4', encoding='utf-8') Mode='w+') as f:f.write ('Duminjun is swimming\ neat Chicken Tonight') running result: same as the result of a mode line

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

forty

forty-one

forty-two

forty-three

forty-four

forty-five

forty-six

forty-seven

forty-eight

forty-nine

fifty

fifty-one

fifty-two

fifty-three

fifty-four

fifty-five

The figure shows:

Write the picture description here.

Third, if the file named 'msg'' contains such contents as' Duminjun is swimming\ neat Chicken tonight', now add the following

'\ nLaura is a playing tennis,What are you dong?' Try the effects of these methods.

Rwith open ('msg', encoding='utf-8', mode='r') as f:f.write ('\ nLaura is a playing tennis,What are you dong?') Running result:

''

Traceback (most recent call last):

F.write ('\ nLaura is a playing tennis,What are you dong?')

Io.UnsupportedOperation: not writable # f is not readable in this instantiated object

''

R + with open ('msg', encoding='utf-8', mode='r+') as f:f.write ('\ nLaura is a playing tennis,What are you dong?') Running result: (no error was reported. The contents of the file are as follows:)

''

Laura is a playing tennis,What are you dong?s swimming

The content added by Chicken eating tonight has been inserted at the front, and the r + mode can be written to the file, but the time to enter the file handle is marked first.

''

If you want to add the content to the end of the text in r + mode, you can read all the content first, the cursor is at the end, and then write the content to the file with open ('msg', encoding='utf-8', mode='r+') as f:f.readlines () f.write ('\ nLaura is a playing tennis,What are you dong?') Run the result (the file content is as follows):

''

Duminjun is swimming

Eat chicken tonight

Laura is a playing tennis,What are you dong?

''

Wwith open ('msg', encoding='utf-8', mode='w') as f:f.write ('\ nLaura is a playing tennis,What are you dong?') The result of the run shows the following in the file:

''

Laura is a playing tennis,What are you dong? # the contents of the original file were all emptied, and the newly added content was written.

''

W+with open ('msg', encoding='utf-8', mode='w+') as f:f.write ('\ nLaura is a playing tennis,What are you dong?') Run result: same as w run result awith open ('msg', encoding='utf-8', mode='a') as f:f.write ('\ nLaura is a playing tennis,What are you dong?')

#

The result of the operation is as follows

''

Duminjun is swimming

Eat chicken tonight

Laura is a playing tennis,What are you dong? # has successfully reached the end of the article

''

A+with open ('msg', encoding='utf-8', mode='a+') as f:f.write ('\ nLaura is a playing tennis,What are you dong?') Run result: the result is the same as that of mode a

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

forty

forty-one

forty-two

forty-three

forty-four

forty-five

forty-six

forty-seven

forty-eight

forty-nine

fifty

fifty-one

fifty-two

fifty-three

fifty-four

fifty-five

fifty-six

fifty-seven

fifty-eight

fifty-nine

sixty

sixty-one

sixty-two

sixty-three

sixty-four

sixty-five

sixty-six

sixty-seven

sixty-eight

sixty-nine

seventy

seventy-one

seventy-two

seventy-three

seventy-four

seventy-five

seventy-six

seventy-seven

seventy-eight

seventy-nine

eighty

eighty-one

Illustration

Write the picture description here.

Write the picture description here.

Fourth, examples: write the function, the user passes in the modified file name, and the content to be modified, execute the function, and complete the batch modification of the whole file.

Def modify_update ():

File_name = input ('please input the file name:'). Strip ()

Modify_content = input ('please input the content to modified:')

New_content = input ('please input new content you want to replace:')

With open ('{} '.format (file_name), encoding='utf-8', mode='r+') as f,\

Open ('msk5', encoding='utf-8', mode='w+') as F1: # Open two file handles, one to read the original document and one to write the modified content

For i in f:

F1.write (i.replace ('{} '.format (modify_content),' {} '.format (new_content)

Loop through each line of the original file while adding a new line to another file. If replace does not find the old word, the string will not be modified, so you do not need the if. Else statement.

''

The operation in one handle will not be emptied every time. It will only be emptied by re-opening a handle in wrecom w + mode and using f.write (), that is to say, there are no two handles.

This is the end of this article on "how to manipulate python files". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

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

Development

Wechat

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

12
Report