Python Classroom 5: File manipulation, ternary operations:

Source: Internet
Author: User


one: file operation:
open () function get file handle: Open ()
file encoding type detection:
Chardet Module third-party module, Need to be installed separately, command line pip install chardet
Import Chardet
f = Open (' Test.txt ', ' RB ') #这里必须是二进制模式打开.
chardet.detect (F.read ()) # Check the character encoding of the file contents.


File operation type:
R Read Only, W write, overwrite, r+ read and write, append. w+ write read, overwrite. A append. b binary Form, WB is written in binary mode, RB reads in binary mode.

" "
Note the position of the cursor when you read the file ,
You can use the Seek () function to set the cursor position, using tell () to see the cursor position .
The cursor position movement is in bytes, so it is important to note that the character is encoded in Chinese:
a utf8 character occupies three bytes, and if the cursor position is within the byte of the Chinese character, there is a garbled problem.
# F.seek (#设置光标位置)
# f.seekable () #检测可否设置光标位置
# Print (F.tell ()) #返回光标位置

# Print (F.read ()) #读取文件所有内容 and is saved as a string.
# Print (f.readable ()) #检测是否可读
# Print (F.readline ()) #读取一行
# Print (F.readlines ()) #把每一行内存读取出来, as a list of elements, to form a list.

# Print (F.mode) #返回文件句柄的模式.
# Print (f.name) #返回句柄打开的文件名
# Print (F.fileno ()) #返回整形的文件描述符
# Print (F.isatty ()) # detects if a file is linked to an end device.


when the file is written : The W method overwrites the file directly, creating the file without the file. A append is written at the end of the file.
generally use read-write mode for file modification r+, you can write files, and avoid overwriting files.
when writing to a file, be sure to specify a character encoding, otherwise it is easy to encode the problem.
Flush () file writes, the system typically caches writes by default in memory, and when the file is finished, it is automatically written to the hard disk when the file handle is closed.
However, in case of abnormal situation, power off and so on, the contents of memory will disappear.
so Python provides the flush () method, which forces the cache content to be flushed directly into the hard disk, reducing unnecessary hassles.

# F.write () #写入, String.
# f.writable () #检测是否可写
# F.writelines () #写入, a list of string compositions.

because the content in the file has a newline character by default at the end of each sentence,
print () also defaults to a \ n line break when printing .
So when you read a file by line, there is an extra line of blank lines.
workaround One, remove the line break at the end of the read file, F.readline (). Strip (). Second, remove the line break in print () print (res,end= ')

File changes , file storage features in the hard disk determine when the file is stored, are overwritten, and no insertions are modified.
If you use the r+ mode seek () directly to the specified location, when you make a change, the discovery will overwrite the contents of that location.
Instead of squeezing the content out to the back.
So when you modify a file, you want to get rid of some of the content, or add some content, squeeze the rest of the content back,
It is generally necessary to read the contents of the file into memory for modification and then write to the hard disk.
two ways, one is all directly read into the memory, the modification is completed and then all written to the hard disk. (consumes more memory)
The other is to open a file more, read a line, make changes, write a new file,
then continue reading the next line, operation, writing, and finally replacing the old file with the new one.
Os.replace (newfile,oldfile) is the equivalent of renaming a new file to an old file, overwriting the original old file.

1 ImportOS2Change_user ='Zhang San'3Change_password ='zhangsan123'4 5file_name ='Io_test.txt'6New_filename ='New%s'%file_name7 8f = open (file_name,'R', encoding='Utf-8')9New_f = open (New_filename,'W', encoding='Utf-8')Ten  forIinchF: One  A     ifChange_userinchI: -i = I.replace (Change_user,'Qianlei')#replace the sentence with the new sentence.  -  the     ifChange_passwordinchI: -i = I.replace (Change_password,'qianlei123') -  - New_f.write (i) +  - #res = F.read () + #New_f.write (RES) A f.close () at new_f.close () -  -Os.replace (New_filename,file_name)#replace the old file with the new file content. 
Modify File Contents


Two: ternary operation :
reduce the amount of code and streamline process control.
ternary refers to the if condition, preceded by the result, after the result.
If the result before the if is established, the result is not established after the else is taken.
A = 3
B = 5
if a>b:
print (a)
Else:
print (b)
Ternary operations:
res = A If a>b else B
Print (res)

























Python Classroom 5: File manipulation, ternary operations:

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.