向文件中插入行的 Pythonic 方式

2022-11-02Python开发问题
1

本文介绍了向文件中插入行的 Pythonic 方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

正如描述所描述的,我想按顺序将文本添加到文件中.比如说,我有一个像这样的文件(不是 HTML,这只是一种想象的语言)让我们称之为 ALLTHEITEMS:

So as the description describes, I would like to add text to a file in a sequential manner. Say, for example I have a file like this (NOT HTML, this is just an imaginary language) lets call it ALLTHEITEMS:

<items>
</items>

说另一个名为ITEMS的文件:

say another file named ITEMS:

banana
apple
blueberry
pickle

而且我已经阅读了项目并创建了一个数组:['banana','apple','blueberry','pickle']

And I already have read through items and have an array created:['banana','apple','blueberry','pickle']

我想遍历数组中的每个项目并将其写入标签之间的 ALLTHEITEMS.

I want to go through each item in the array and write it to ALLTHEITEMS in between the tags.

所以最后 ALLTHEITEMS 应该是这样的:

So in the end ALLTHEITEMS should look like:

<items>
banana
apple
blueberry
pickle
</items>

最pythonic的方式是什么?

What is the most pythonic way?

推荐答案

我会这样做:

with open(outputfile,'w') as out, open(inputfile) as f:
    for line in f:
        out.write(line)
        if tag_match(line):  #Somehow determine if this line is a match where we want to insert text.
           out.write('
'.join(fruits)+'
')

可能想出一个方法来让它更快,但我怀疑它是否值得.这很简单,易于阅读,并且可以完成工作.pythonic"对我来说足够了:-)

You might come up with a way to make it faster, but I doubt it is worthwhile. This is simple, easy to read, and gets the job done. "pythonic" enough for me :-)

这篇关于向文件中插入行的 Pythonic 方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10