inplace text filter - without writing file
MRAB
python at mrabarnett.plus.com
Sat Oct 1 21:14:27 EDT 2016
On 2016-10-02 01:21, Sayth Renshaw wrote:
> Hi
>
> I have a fileobject which was fine however now I want to delete a line from the file object before yielding.
>
> def return_files(file_list):
> for filename in sorted(file_list):
When joining paths together, it's better to use 'os.path.join'.
> with open(dir_path + filename) as fd:
> for fileItem in fd:
> yield fileItem
>
> Ned gave an answer over here http://stackoverflow.com/a/6985814/461887
>
> for i, line in enumerate(input_file):
> if i == 0 or not line.startswith('#'):
> output.write(line)
>
> which I would change because it is the first line and I want to rid <!--
>
> for i, line in enumerate(input_file):
> if line.startswith(<!--'):
> output.write(line)
>
> However I do not want to write the file I want to restore all the enumerated files back to the fileItem I need to yield.
>
> How do I do this?
>
You use the logic of the answer from StackOverflow in your
'return_files' function:
def return_files(file_list):
for filename in sorted(file_list):
with open(dir_path + filename) as fd:
for fileItem in fd:
if keep_item(fileItem):
yield fileItem
If you need to know the line number when deciding whether to keep a
line, use enumerate too:
def return_files(file_list):
for filename in sorted(file_list):
with open(dir_path + filename) as fd:
for i, fileItem in enumerate(fd):
if keep_item(fileItem, i):
yield fileItem
More information about the Python-list
mailing list