Python extract specified content from text
There is a test.txttext with the content
Since the text format is relatively standard, the second column is the password. Now you need to extract the second column password of all lines and save it to another password.txtfile.
#code
file_test = open('test.txt',mode='r',encoding='GBK')password = open('password.txt',mode='a')for line in file_test:
x = line.split("----")
password.write(x[1])
password.write("\n")
print(x[1])password.close()file_test.close()
#Summary (Python3)
#1.open() function
grammar
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Common parameter description
file:Required, file path (relative or absolute).
mode:Optional, file open mode
buffering:Optional, set buffer
encoding:Optional, file encoding format
The mode parameters are:
a:Append method. If the file exists, the new content is written after the existing content; if the file does not exist, a new file is created and written.
b:binary way.
r:Read-only mode. The file pointer will be placed at the beginning of the file.
r+:Read and write. The pointer to the file will be placed at the beginning of the file. If the file does not exist, an error will be reported.
rb:Read-only opened in binary format. The file pointer will be placed at the beginning of the file, generally used for non-text files such as pictures.
w:write only. If the file already exists, it is edited from the beginning and the original content is deleted; if the file does not exist, a new file is created.
w+:Read and write. If the file already exists, it is edited from the beginning and the original content is deleted; if the file does not exist, a new file is created.
wb+:Read-write opened in binary format. If the file already exists, it will be edited from the beginning, and the original content will be deleted; if the file does not exist, a new file will be created; generally used for non-text files such as pictures.
Notice:
When using the open() function, be sure to close the file object, that is, call the close() function.
#2.split()函数
grammar
str.split(str="", num=string.count(str))
parameter
str: Delimiter, which defaults to all empty characters, including spaces, newlines (\n), tabs (\t), etc.
num: Number of divisions. Defaults to -1, which separates all.
return value
Returns a list of split strings.
0 Comments