Python base (12) file

1. read the file

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

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

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

2. After the file pointer will change to read the file

# 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. Write file

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

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

# 3. 关闭
file.close()

4. Branch read the file

file = open("README")

while True:
    text = file.readline()

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

    print(text)

file.close()

5. Copy the file

# 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. copying large files

# 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 string

# *-* coding:utf8 *-*

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

print(hello_str)

for c in hello_str:
    print(c)

8.eval Calculator

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

print(eval(input_str))

Guess you like

Origin blog.csdn.net/qq_34562355/article/details/90479587