如何打开作品?
How with open works?
今天我试图打开一个文件并根据文件的数据构建一些列表。我正在使用 with 语句。但是我有以下疑问:
如果我写下面的代码:
def Preset_wheel_filler(self):
"""
Complete the Preset_wheel and also apply preset values when one
preset is selected.
"""
with open('Preset.txt', 'r') as PresetFile:
Presets = [line.split()[1:] for line in PresetFile if 'name:'
in line.split()]
with open('Preset.txt', 'r') as PresetFile:
channel_list = ['1', '2', '3', '4', '5', '6', '7', '8']
Preset_values = [line.split() for line in PresetFile for
y in channel_list if y in line.split()]
print(len(Preset_values))
最后创建的列表长度为 16。(正确)
现在,如果我像这样重新排列代码:
def Preset_wheel_filler(self):
"""
Complete the Preset_wheel and also apply preset values when one
preset is selected.
"""
with open('Preset.txt', 'r') as PresetFile:
Presets = [line.split()[1:] for line in PresetFile if 'name:'
in line.split()]
channel_list = ['1', '2', '3', '4', '5', '6', '7', '8']
Preset_values = [line.split() for line in PresetFile for
y in channel_list if y in line.split()]
print(len(Preset_values))
打印长度为0
我的问题是:为什么要写两次with open语句?
提前致谢。
文件是基于流的。一旦你读取了文件中的所有数据,它的位置指针就在末尾,再也无法读取任何内容。你 "could" 寻求 0 来解决这个问题,但是 - 你一开始就有完整的行,只需从中解析两件事。
PresetFile.seek(0) # goes back to the beginning of the file.
见https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects
有关如何使用 seek 和 maybee peek 的详细信息 https://docs.python.org/3/library/functions.html#open
再次。
今天我试图打开一个文件并根据文件的数据构建一些列表。我正在使用 with 语句。但是我有以下疑问:
如果我写下面的代码:
def Preset_wheel_filler(self):
"""
Complete the Preset_wheel and also apply preset values when one
preset is selected.
"""
with open('Preset.txt', 'r') as PresetFile:
Presets = [line.split()[1:] for line in PresetFile if 'name:'
in line.split()]
with open('Preset.txt', 'r') as PresetFile:
channel_list = ['1', '2', '3', '4', '5', '6', '7', '8']
Preset_values = [line.split() for line in PresetFile for
y in channel_list if y in line.split()]
print(len(Preset_values))
最后创建的列表长度为 16。(正确)
现在,如果我像这样重新排列代码:
def Preset_wheel_filler(self):
"""
Complete the Preset_wheel and also apply preset values when one
preset is selected.
"""
with open('Preset.txt', 'r') as PresetFile:
Presets = [line.split()[1:] for line in PresetFile if 'name:'
in line.split()]
channel_list = ['1', '2', '3', '4', '5', '6', '7', '8']
Preset_values = [line.split() for line in PresetFile for
y in channel_list if y in line.split()]
print(len(Preset_values))
打印长度为0
我的问题是:为什么要写两次with open语句?
提前致谢。
文件是基于流的。一旦你读取了文件中的所有数据,它的位置指针就在末尾,再也无法读取任何内容。你 "could" 寻求 0 来解决这个问题,但是 - 你一开始就有完整的行,只需从中解析两件事。
PresetFile.seek(0) # goes back to the beginning of the file.
见https://docs.python.org/3/tutorial/inputoutput.html#methods-of-file-objects 有关如何使用 seek 和 maybee peek 的详细信息 https://docs.python.org/3/library/functions.html#open 再次。