Skip to content

文件

运行

新建文件

# test.py

def test():
    print('Hello World')

test()

运行文件

python test.py
Hello World

使用 -c 参数运行 python 代码

python -c "
def test():
    print('Hello World')

test()
"
Hello World

Python 用井号(#)进行注释,最好单独占据一行。

新建文件

# test.py

# 输出
print('Hello World') # 打印

运行文件

python test.py
Hello World

读写

新建文件,写入数据,保存关闭文件。

f = open('a.txt', 'w')

f.write('Hello\n')
f.write('World\n')

f.close()

open 函数参数:

  • 默认是只读模式 r ,只写模式为 w ,追加模式为 a ,排他性创建 x 。
  • 默认是文本模式 t ,二进制模式为 b 。
  • 读写为 +

使用 with 语句,可以自动关闭文件,保证安全。

with open('a.txt', 'w') as f:
    f.write('Hello\n')
    f.write('World\n')

读取文件

f = open('a.txt')

print(f.read())

f.close()
Hello
World

其中 read 是指针式的,再次读取会读取到空文本。

f = open('a.txt')

print(f.read())
print(f.read())

f.close()
Hello
World

使用 with 语句,一次性读取

with open('a.txt') as f:
    print(f.read())
Hello
World

使用 with 语句,逐行读取

with open('a.txt') as f:
    for line in f:
        print(line)
Hello

World

联系 math@baima.site