Some pit python open function

(1 ) Problems path 

open a file with a directory file py same time, the following: 

TXT = open ( ' /filtered_words.txt ' , ' RB ' ) 
words = txt.readline () 
Filtered = []
 for Word in words: 
filtered.append (Word) 
txt.close () 
Print (Filtered) 

being given 
FileNotFoundError: [Errno 2] No SUCH File or Directory: ' /filtered_words.txt ' 

where a wrong place, should be written 
TXT = Open ( ' filtered_words.txt ' ,' RB ' ) 
may also utilize the absolute path 

TXT = Open ( ' E: \\ \\ python_project Test \ filtered_words.txt GitHub \\ ' , ' RB ' ) 
so that no error will be 
with a backslash, so that no error will be 

TXT = open ( ' E: /python_project/test/github/filtered_words.txt ' , ' rb ' ) 

( 3 ) to open the file format 

of the document content is Chinese characters, use UTF - 8 format, if rb permission open file, print characters it will become a digital 

TXT = Open ( ' filtered_words.txt ' , ' RB ' ) 
words =txt.readline () 
print result is: 
[ 229, 140, 151, 228, 186, 172, 13, 10 ] 

 

with r being given permission to open 

a UnicodeDecodeError: ' GBK ' CODEC CAN ' T in decode byte position 0x98 16: multibyte The Illegal sequence 
in open time, plus a coding 

TXT = open ( ' filtered_words.txt ' , ' R & lt ' , encoding = ' UTF-. 8 ' ) 
words = txt.readline () 
print out the result 
[ ' North ' , ' Beijing ' , '\n'] 

The readline into read function, the print result is 

[ ' North ' , ' Beijing ' , ' \ n- ' , ' process ' , ' Order ' , ' member ' , ' \ n- ' , ' male ' , ' service ' , ' member ' ] 

own Baidu the Read (), the difference readline (), readlines (), and finally finishing code 

TXT = Open ( ' filtered_words.txt ' , 'rb', encoding = ' UTF-. 8 ' ) 
WOR = txt.readlines () 
Filtered = []
 for Word in WOR: 
Word = word.strip ( ' \ n- ' ) 
filtered.append (Word) 
Print (Word) 
txt.close ( ) 
Print (Filtered) 
print result is [ ' Beijing ' , ' programmer ' , ' Civil ' ] 


final code is as follows: 
class senseWord ():
 DEF  the __init__ (Self): 
self.list= []
file = open('filtered_words.txt','r',encoding='UTF-8')
words = file.readlines()
for word in words:
word = word.strip('\n')
self.list.append(word)

def checkwords(self,str):
if str in self.list:
return True
else:
return False


if __name__ == '__main__':
sense = senseWord()
str = input('input a string')
if sense.checkwords(str) == True:
print('freedom')
else:

 

————————————————

Guess you like

Origin www.cnblogs.com/Rivend/p/11785078.html