【发布时间】:2022-01-20 15:55:22
【问题描述】:
我有以下代码将raw_file.txt 转换为processed_file.txt。
问题一:
除了item_location,我还需要item_id(作为str,而不是int)在处理过的文件中,也许作为列表,所以它看起来像WANTED_processed_file.txt
def process_file(raw_file, processed_file, target1):
with open(raw_file, 'r') as raw_file:
with open(processed_file, 'a') as processed_file:
for line in raw_file:
if target1 in line:
processed_file.write(line.split(target1)[1])
process_file('raw_file.txt', 'processed_file.txt', 'item_location: ')
通过添加另一个带有target2 的if 语句,内容将附加在target1 下方(如预期的那样),但我实际上不知道如何将其设为列表。
问题 2:
使用我当前的代码,我只能处理与该行对应的字符串,但由于WANTED_processed_file.txt 包含多个列表,我需要对其进行调整。
def my_function():
print(i)
with open('processed_file.txt', "r") as processed_file:
items = processed_file.read().splitlines()
for i in items:
my_function()
这是我尝试过的,但我没有得到想要的结果:
def my_function():
print(f'Item {i[0]} is located at {i[1]}')
with open('WANTED_processed_file.txt', "r") as processed_file:
items = processed_file.read()
for i in items:
my_function()
raw_file.txt:
ITEM:
item_id: 0001
item_location: first location
item_description: something
ITEM:
item_id: 0002
item_location: second location
item_description: something else
processed_file.txt:
first location
second location
WANTED_processed_file.txt:
['0001', 'first location']
['0002', 'second location']
感谢您,并为冗长的帖子道歉
【问题讨论】:
-
请不要在循环的每次迭代中打开文件。在进行文件 I/O 时使用
with块
标签: python list file multiline