1cm69 1cm69 - 1 month ago 6
Python Question

Only Append to File Once from Multiple Entries in Python

I have a text file that contains many lines of data, 5 indexes or columns.

I am trying to read through these lines looking for a particular string and then append this string to another file.
What I have works in principle but the problem is that sometimes the search string appears numerous times in the file I am reading from and my function causes the write to file to be appended by the same number of times as the string appears.

I need to just be able to search for the string and if it's found even more than once, only one entry is appended to the write to file.

Here is sample code from read from file, the one I am searching through:

00:00,19.90,990.49,59.16,11.78,No
01:00,19.92.991.00,59.75,11.90,Yes
02:00,19.76,991.21,58.87,10.95,No
03:00,19.34,989.97,57.00,10.64,Yes


here is the code I am using that is supposed to search through the above code for the occurrence of 'Yes' in index[5]
When it find the word 'Yes' it then append this to another file but should only do it the once even if there are multiple entries of the word 'Yes'

IsWet = 'Yes'
with open(dPath + FileDate + '.txt', 'r') as Precipitation:
for row in Precipitation:
if IsWet == str(row.strip().split(',')[5]):
with open(dPath + 'Wet.txt', 'a') as outfile:
outfile.write(wDay + ',' + IsWet)


Any assistance would be appreciated, thanks.

sal sal
Answer

If you are positive that you only need it once even if multiple are present, you can simply break your loop above and be done, which also helps with performance:

IsWet = 'Yes'
with open(dPath + FileDate + '.txt', 'r') as Precipitation:
    for row in Precipitation:
        if IsWet == str(row.strip().split(',')[5]):
            with open(dPath + 'Wet.txt', 'a') as outfile:
                outfile.write(wDay + ',' + IsWet)
            break