这是一个有超过1000行的大文件。只有在不存在元素的情况下,我才需要在水果容器中添加元素apple,而不更改现有元素的文件布局结构或位置。
如果有什么不清楚的话,请告诉我.感谢您的支持,提前!
发布于 2020-08-04 17:14:15
由于您有一个大文件,我们将单独处理每个容器,而不是在内存中加载整个文件。我们可以很容易地在Python3中做到这一点。将其保存在process.py中,数据保存在fruits_file.txt中
import sys
# This function checks if "apple" not in container then append it.
def add_apple_and_print(header, container):
if container is not None:
if not any(fruit.startswith("apple") for fruit in container):
container.append('apple: ripe fruit, vitamin a, b, c')
print("\n"+header+"\n")
print("\n\n".join(container))
# Open the file for reading
with open(sys.argv[1]) as f:
header = None # Initialize header with None
container = None # Initialize the container with None
for line in f: # Read line by line
line = line.strip() # Remove trailing spaces
if len(line) > 0:
if "fruits :" in line: # if line contains "fruits :"
add_apple_and_print(header, container) # Print privious container
header = line # Set header
container = [] # Create a new container for current fruit section
else:
container.append(line) # Add fruits to container
add_apple_and_print(header, container) # Print last container然后
python3 process.py fruits_file.txt > fruits_file_with_apple.txt编辑:在早期的剧本中,“苹果”和“菠萝”是匹配的。因此没有被添加到这样的容器中。修改了脚本。
从SvenMarnach在stackoverflow.com上的答案中获得提示
https://askubuntu.com/questions/1264509
复制相似问题