Is there a way to run a python script on every text file in a folder? So for example I want to delete the first 5 lines of every text file in that folder what would I have to do?
-
This partially depends on how you define text file; is it just files that end a .txt, all files (but not directories), or do you need to do some more inspection to separate binary files from test files? Also, look at os.listdir()Foon– Foon2014-03-14 18:20:03 +00:00Commented Mar 14, 2014 at 18:20
-
its just all files that end in .txtuser3413472– user34134722014-03-14 18:20:57 +00:00Commented Mar 14, 2014 at 18:20
Add a comment
|
3 Answers
To elaborate om tmarstrand's answer:
import glob
import os.path
import sys
dir_of_interest = sys.argv[1]
files = glob.glob(os.path.join(dir_of_interest, "*.txt"))
for file in files:
with open(file, "rw") as f:
f.writelines(f.readlines()[5:])
2 Comments
user3413472
After running your script I got the following error message: ~/Documents/allfolder.py:8: IndentationError: expected an indented block
TankorSmash
@user3413472 try it again now, I pasted it in too hastily.