Python基础(12)文件

1.读取文件

# 1. 打开文件
file = open("README")

# 2. 读取文件内容
text = file.read()
print(text)

# 3. 关闭文件
file.close()

2.读取文件后文件指针会改变

# 1. 打开文件
file = open("README")

# 2. 读取文件内容
text = file.read()
print(text)
print(len(text))

print("-" * 50)

text = file.read()
print(text)
print(len(text))

# 3. 关闭文件
file.close()

3.写入文件

# 1. 打开
file = open("README", "a")

# 2. 写入文件
file.write("123 hello")

# 3. 关闭
file.close()

4.分行读取文件

file = open("README")

while True:
    text = file.readline()

    # 判断是否读取到内容
    if not text:
        break

    print(text)

file.close()

5.复制文件

# 1. 打开
file_read = open("README")
file_write = open("REAMDE[复件]", "w")

# 2. 读、写
text = file_read.read()
file_write.write(text)

# 3. 关闭
file_read.close()
file_write.close()

6.复制大文件

# 1. 打开
file_read = open("README")
file_write = open("REAMDE[复件]", "w")

# 2. 读、写
while True:
    # 读取一行内容
    text = file_read.readline()

    # 判断是否读取到内容
    if not text:
        break

    file_write.write(text)

# 3. 关闭
file_read.close()
file_write.close()

7.python2字符串

# *-* coding:utf8 *-*

# 引号前面的u告诉解释器这是一个utf8编码格式的字符串
hello_str = u"hello世界"

print(hello_str)

for c in hello_str:
    print(c)

8.eval计算器

input_str = input("请输入算术题:")

print(eval(input_str))

猜你喜欢

转载自blog.csdn.net/qq_34562355/article/details/90479587
今日推荐