0

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?

2
  • 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() Commented Mar 14, 2014 at 18:20
  • its just all files that end in .txt Commented Mar 14, 2014 at 18:20

3 Answers 3

3

Simply match all the files in the directory using the glob module

import glob
import os
import os.path
import sys

dir_of_interest = sys.argv[1]
files = glob.glob(os.path.join(dir_of_interest, "*.txt"))
for f in files:
    ... do stuff ...
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

import os
for file in os.listdir("path_to_your_dir"):
    if file.endswith(".txt"):
        #do_simething

Comments

0

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

After running your script I got the following error message: ~/Documents/allfolder.py:8: IndentationError: expected an indented block
@user3413472 try it again now, I pasted it in too hastily.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.