Tag: line mode empty start imp create ODI pytho assignment
---restore content starts---
First, the document processing process:
- Open the file, get the file handle and assign a value to a variable
- Manipulating a file with a handle
- Close File
Second, the basic operation:
1. Basic process of file operation.
f = open ('Chenli.txt')#Open FileFirst_line =F.readline ()Print('First line :', First_line)#read a linePrint('I'm the dividing line .'. Center (50,'-')) Data= F.read ()#Read all the rest of the content, do not use when the file is largePrint(data)#Print Read contentf.close ()#Close File
2, the software default format.
# do not specify open encoding, default to use operating system encoding, Windows Gbk,linux for Utf-8, and interpreter encoding independent F=open ('chenli.txt' , encoding='gbk'# is also GBK encoded by default in Windows and does not specify encoding at this time . F.read ()
3 File open mode.
1 File handle = open (' file path ' mode ')
When you open a file, you need to specify the file path and how you want to open the file, and then open it to get the file handle and manipulate it later through the file handle.
The mode of opening the file is:
r+, open the read-write file. The file pointer is placed at the beginning of the file.
w+ Open the file that was written and read. If the file exists, overwrite the existing file. If the file does not exist, create a new file for reading and writing.
x+ write "readable, writable"
A + opens a file for appending and reading. If the file exists, the file pointer is at the end of the file. The file opens in attach mode. If the file does not exist, it creates a new file for reading and writing
3. Context Management
With open ('a.txt','w') as F: Pass
With open ('a.txt','r') as Read_f,open ('b.txt ','w') as Write_f: data=read_f.read () Write_f.write (Data
4. Modification of documents
ImportOswith Open ('a.txt','R', encoding='Utf-8') as Read_f, open ('. A.txt.swap','W', encoding='Utf-8') as Write_f: forLineinchRead_f:ifLine.startswith ('Hello'): Line='hahaha \ n'Write_f.write (line) Os.remove ('a.txt') Os.rename ('. A.txt.swap','a.txt')
---restore content ends---
Python basic files