[Python] python3 file operations: input files from the keyboard, open and close files, read and write files, rename and delete files, etc,

Source: Internet
Author: User

[Python] python3 file operations: input files from the keyboard, open and close files, read and write files, rename and delete files, etc,
1. Input from the keyboard

Python 2 has two built-in functions used to read data from standard input, which are by default from the keyboard. These two functions are: input () and raw_input ().
In Python 3, The raw_input () function is not recommended. All input () functions that can be read from the keyboard are converted to the string type.


The figure shows that even if we input the 123456789 input () function, we still fully regard it as a string.

2. Open and Close files

Python provides the basic functions and methods required for default file operations. You can use a file object to perform most file operations.

The following method is a Python built-in method, without importing a package.

1. Open a file

Before reading or writing a file, you must use the Python built-in open () function to open the file. This function creates a file object that is used to call other supported methods associated with it.


Enter open () in Pycharm IDE, press Ctrl, and click open to view the open method.

Parameters:

File: the parameter is a string type and specifies the name of the file to be accessed.

Mode: determines the file opening mode, including reading, writing, and appending. A complete list of possible values is shown in the following table. This is an optional parameter. The default file access mode is (r-that is, read-only ).

Generally, you only need to enter these two parameters.

The following is a list of file opening modes:


2. File object attributes

After opening a file and having a file object, you can obtain various information related to the file.
The following lists all attributes related to file objects:


3. close () method

The close () method of the file object refreshes any unwritten information and closes the file object. Then, the file object cannot be written.
When the referenced object of the file is re-allocated to another file, Python will automatically close the file. However, using the close () method to close a file is a good habit.

Syntax: fileName. close ()

3. Read and Write files

File objects provide a set of access methods to facilitate code writing. The read () and write () methods are used to read and write files respectively.

1. write () method

The write () method writes any string to the open file. It is important to note that Python strings can be binary data, not just text.
The write () method does not add a line break ('\ n') at the end of the string ')


Only one parameter is required, that is, the text content to be written.

PS. When opening a file, you must grant the write permission.

2. read () method

The read () method is used to read a string from an opened file. It is important to note that Python strings can be binary data in addition to text data.


Here, the transmitted parameter n is the number of bytes read from the opened file.

This method starts from the beginning of the file. If n is not specified, the full text is read.

4. File Location

Tell () method

It is used to obtain the current position of the file. In other words, the next read or write will occur after the beginning of the file.
Seek (offset [, from]) method:

Change the current file location. The offset parameter indicates the number of bytes to be moved. The from parameter specifies the reference location of the byte to be moved.
From parameter:

If this parameter is set to 0, the start of the file is used as the reference position. If this parameter is set to 1, the current position is used as the reference position. If set to 2, the end of the file will be used as the reference location.

5. Rename and delete an object

The Python OS module provides methods for executing file processing operations (such as renaming and deleting files. To use this module, you must first import it and then call any related functions.

1. rename () method

The rename () method has two parameters: the current file name and the new file name.


2. remove () method

The remove () method provides the name of the file to be deleted as a parameter to delete the file.


6. Supplement 1. Python file object Method


2. Method of the OS module (Omitted part)


7. Code for reading and writing files (in combination with the file selection dialog box)


1 # coding: utf-8
 2 # author: Twobox
 3
 4 import wx
 5 import os
 6
 7 class MyWin (wx.Frame):
 8 def __init __ (self, parent, title):
 9 super (MyWin, self) .__ init __ (parent = parent, title = title)
10 self.wildcard = "Text file (* .txt) | * .txt"
11 self.initUI ()
12 self.Show ()
13
14 def initUI (self):
15 panel = wx.Panel (self)
16
17 vbox = wx.BoxSizer (wx.VERTICAL)
18 panel.SetSizer (vbox)
19
20 hbox1 = wx.BoxSizer (wx.HORIZONTAL)
21 hbox2 = wx.BoxSizer (wx.HORIZONTAL)
22 vbox.Add (hbox1, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 0)
23 vbox.Add (hbox2, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 0)
twenty four 
25 self.fileAddress = wx.TextCtrl (panel)
26 btn1 = wx.Button (panel, label = "Open", id = wx.ID_OPEN)
27 btn2 = wx.Button (panel, label = "Save", id = wx.ID_SAVE)
28 hbox1.Add (self.fileAddress, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
29 hbox1.Add (btn1, proportion = 0, flag = wx.EXPAND | wx.UP | wx.DOWN, border = 5)
30 hbox1.Add (btn2, proportion = 0, flag = wx.EXPAND | wx.ALL, border = 5)
31
32 # content content conter center
33 self.content = wx.TextCtrl (panel, style = wx.TE_MULTILINE | wx.TE_DONTWRAP)
34 hbox2.Add (self.content, proportion = 1, flag = wx.EXPAND | wx.ALL, border = 5)
35
36 self.Bind (wx.EVT_BUTTON, self.eventButtonOpen, btn1)
37 self.Bind (wx.EVT_BUTTON, self.eventButtonSave, btn2)
38
39 def eventButtonOpen (self, event):
40 wildcard = self.wildcard
41 dlg = wx.FileDialog (parent = self, message = "Please Select File", defaultDir = os.getcwd (), wildcard = wildcard, style = wx.FD_OPEN)
42
43 if dlg.ShowModal () == wx.ID_OK:
44 # dlg.SetPath ("1.txt") # You can change the selected file address
45 # print (dlg.GetPath ())
46 self.fileAddress.SetValue (dlg.GetPath ())
47 with open (dlg.GetPath (), "r") as f:
48 self.content.SetValue (f.read ())
49 dlg.Destroy ()
50
51 def eventButtonSave (self, event):
52 wildcard = self.wildcard
53 dlg = wx.FileDialog (parent = self, message = "Please ...", defaultDir = os.getcwd (), wildcard = wildcard, style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
54
55 if dlg.ShowModal () == wx.ID_OK:
56 filePath = dlg.GetPath ()
57 self.fileAddress.SetValue (filePath)
58 with open (filePath, "w") as f:
59 f.write (self.content.GetValue ())
60 dlg.Destroy ()
61
62 def main ():
63 app = wx.App ()
64 MyWin (None, "File Dialog-Test")
65 app.MainLoop ()
66
67 if __name__ == '__main__':
68 main () 

 

8. Postscript

It is still comprehensive. Generally, most operations on files can be completed in the future.

O. O forgot to post a blog yesterday (it is actually a waste ).

Author reference: http://www.yiibai.com/python/python_files_io.html

Reprinted please indicate the source (● 'authorization' ●): http://www.cnblogs.com/Twobox/

14:55:29


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.