# -*- coding: utf-8 -*-
# read txt file
def readTextFile(file):
f = open(file, 'r')
# 尽可能多的读取文件的内容,一般会将整个文件内容都会读取
context = f.read()
print(context)
f.close()
def readTextFileByLines(file):
f = open(file, "r")
lines = f.readlines() # 注意会读取'\n',需要去掉'\n'才是真正的文件内容
# line是一个列表,每个元素就是文件的一行
fdataList = []
for i in range(0, len(lines)):
lines[i] = lines[i].rstrip('\n')
fdataList.append(float(lines[i])) # 转换为float类型数字,因为读进来时是字符串类型
# print(lines)
# print(file, " has ", len(lines), " lines.")
print(fdataList)
print(file, " has ", len(fdataList), " lines.")
f.close()
def readTextFileByLine(file):
f = open(file)
line = f.readline()
fdataList = []
while line:
fdataList.append(float(line))
line = f.readline()
print(fdataList)
print(file, " has ", len(fdataList), " lines.")
f.close()
# 尽管有中文字符,但是读入进来是没有问题的,注意说明编码方式"# -*- coding: utf-8 -*-"
def readZHCTextFile(file):
#f = open(file, "r", encoding='UTF-8')
f = open(file, "r")
lines = f.readlines()
for i in range(0, len(lines)):
lines[i] = lines[i].rstrip('\n')
print(lines)
f.close()
def writeTextFile(file):
f = open(file, "w")
f.write('Hello, world!')
f.write("Good!")
f.write(" HaHa...")
f.write("\nI am a new line\n")
f.write("你好") # 写入中文
f.write("\n这是中文字符,你能看到吗\n")
f.close()
def writeAppendTextFile(file):
f = open(file, "a+")
f.write("我是追加进来的内容哦\n")
f.write("请仔细阅读本软件的协议说明!")
f.seek(0, 0)# 把文件指针从末尾移到开头
print(f.read())
f.seek(0, 0)# 把文件指针从末尾移到开头
# 注意写入的时候都是追加在文件末尾的
f.write("I am the first line...\n")
f.close()
def writeTextFileByLine(file):
f = open(file, "w")
f.writelines("Hello, python!")
f.writelines(["Welcome to python world", "Let'u start the python programing journey"])
f.writelines(["\n second line\n", "thrid line"])
f.close()
def main():
file1 = "s1.txt"
# readTextFile(file1)
# readTextFileByLines(file1)
# readTextFileByLine(file1)
file2 = "pythonWriteTestTxt.text"
# writeTextFile(file2)
# readZHCTextFile(file2)
# writeAppendTextFile(file2)
file3 = "hello.txt"
writeTextFileByLine(file3)
if __name__ == '__main__':
main()