I'm using os and glob to create a list of CSVs first and then using a simple for loop I go through all the files in the path applying my code.
path = r'my path'
os.chdir(path)
FileList = glob.glob('*.csv')
for fname in FileList:
Session = pd.read_csv(fname, header = 3, usecols = [0, 1])
Session = Session[Session['System'].str.contains('Day', na=False)]
Session = Session['No System Name'].tolist()
CRFs = sum(["CRF" in x for x in Session])
...
df.to_csv(path + 'test_' + fname , index = 0)
Is there a way I can make the loop skip a file if the length of Session equals to CRFs the loop will just stop and restart with the next file in the FileList? I've tried doing it like this using both break and continue but neither did anything:
for fname in FileList:
Session = pd.read_csv(fname, header = 3, usecols = [0, 1])
Session = Session[Session['System'].str.contains('Day', na=False)]
Session = Session['No System Name'].tolist()
CRFs = sum(["CRF" in x for x in Session])
if CRFs == len(Session) is True:
continue(or break)
...
df.to_csv(path + 'test_' + fname , index = 0)
Many thanks in advance!
Instead of below in your code:
if CRFs == len(Session) is True:
continue
Just do:
if CRFs == len(Session):
continue
Yes! I believe the continue statement is exactly what you are looking for.
When executed, the continue
statement will cause execution of the current loop iteration to end, and the next iteration to begin.
Example from the python docs:
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
...
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
You can break the main cycle when some condition happens, take a look at the official documentation regarding this topic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.