文件操作
1.with打开
with open(r'E:\py\text_files\pi.txt') as file_object: # 在冒号前加r表示以原始字符串方式指定路径,否则会出现\t的转义符报错或者用\\表示路径 contents = file_object.read() print(contents.strip())
2.逐行读取及打印
filename = 'E:\py\\text_files\pi.txt' with open(filename) as file_object: # 在冒号前加r表示以原始字符串方式指定路径,否则会出现\t的转义符报错或者用\\表示路径 contents = file_object.readlines() # 逐行读取 for i in contents: print(i.strip()) # 逐行打印,去除空行的空格
3.调整指针
filename = r'E:\py\text_files\pi.txt' with open(filename) as file_object: # 在冒号前加r表示以原始字符串方式指定路径,否则会出现\t的转义符报错或者用\\表示路径 contents = file_object.readlines() # 逐行读取 # file_object.seek(20)#调整指针位置 print(file_object.tell()) # 42获取指针位置 a = '' for i in contents: a = a + i.strip() # 拼接字符串 print(a) # 3.141592653589793238462643383279 print(len(a)) # 32
4.替换字符
with open(r'e:\py\text_files\pi.txt', 'r', encoding='utf-8') as abc: for i in abc.readlines(): c = i.replace('Python', 'C++') print(c.strip()) '''In C++ you can create class In C++ you can use loops In C++ you can look at function'''