1 class ReadFile(): 2 """读取文件""" 3 4 def __init__(self,file_path): 5 self.file_path = file_path 6 7 def read_file(self): 8 """ 9 读取整个文件 10 使用关键字with时,open()返回的文件对象只在with代码块内可用 11 """ 12 with open(self.file_path) as file_object: 13 contents = file_object.read() 14 """ 15 方法 rstrip() 删除(剥除)字符串末尾的空白 16 方法 lstrip() 删除(剥除)字符串开头的空白 17 方法 strip() 删除(剥除)字符串开头和末尾的空白 18 """ 19 print(contents.rstrip()) 20 21 def read_file_line_1(self): 22 with open(self.file_path) as file_object: 23 for line in file_object: 24 print(line) 25 26 def read_file_line_2(self): 27 with open(self.file_path) as file_object: 28 """方法readlines()从文件中读取每一行,并将其存储在一个列表中""" 29 lines = file_object.readlines() 30 return lines 31 32 33 """打开在程序文件所属目录中的文件""" 34 file_path_1 = 'pi_digits.txt' 35 36 contents = ReadFile(file_path_1) 37 contents.read_file() 38 contents.read_file_line_1() 39 print(contents.read_file_line_2()) 40 41 pi_string = '' 42 for line in contents.read_file_line_2(): 43 pi_string += line.strip() 44 45 print(pi_string) 46 print(len(pi_string)) 47 print(pi_string[:10]+'...') 48 49 """打开不在程序文件所属目录中的文件""" 50 51 r""" 52 在python中\是转义符,\U表示其后是UNICODE编码 53 因此\User这里会出错,在字符串前面加个r表示不进行转义就可以了 54 备注中含\,前面也要加r 55 """ 56 57 58 """ 59 用绝对文件路径打开文件 60 字符串分成两行时, \ 要在下一行 61 """ 62 63 file_path_2 = r"C:\Users\Administrator\Desktop\python\python work\10" 64 file_path_2 += '\pi_digits.txt' 65 66 contents = ReadFile(file_path_2) 67 contents.read_file() 68 69 """ 70 用相对文件路径打开文件 71 字符串分成两行时, \ 要在下一行 72 """ 73 74 file_path_3 = r"1\pi_digits.txt" 75 76 contents = ReadFile(file_path_3) 77 contents.read_file()
python读取文件和消除空格
猜你喜欢
转载自www.cnblogs.com/merryconei123/p/13201722.html
今日推荐
周排行