首页 > 解决方案 > When using open() as f: does f represent a new variable being created?

问题描述

I am new(ish) to Python and I'm just trying to figure out how things work. When I use:

with open('C:\\Users\\KB\\Documents\\DataProcessing.txt', 'r') as f:

is f a new variable being created? Could I use any variable in its place? I've seen 'file' used as-well so I'm just wondering if this is an arbitrary name being assigned to a newly created variable? Could it be named anything or does it have to be f?

标签: pythonpython-3.x

解决方案


是否正在创建新变量?我可以使用任何变量代替它吗?

是的

with open('testfile.txt') as f:
    print(f.read())

相当于

with open('testfile.txt') as lmnopqrstuvwxyz:
    print(lmnopqrstuvwxyz.read())

推荐阅读