-1

I have 500 text files in a folder. How do I find out how many lines each text file have, and delete them if it has more than 300 lines.

import os

path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
    with open(os.path.join(path, file), 'r',encoding='utf-8') as f:
      #find the lines of each file
Chang
  • 77
  • 6

3 Answers3

2

Unfortunately you will have to read the file to see how many lines it has. In your case, you could skip it once you reach 300.

Sample code to get line count

file = open("sample.txt", "r")
line_count = 0
for line in file:
    if line != "\n":
        line_count += 1
file.close()

print(line_count)
Saurabh
  • 49
  • 2
1
import os

path = "All_TSV_Files"
files = [file for file in os.listdir(path) if file.endswith(".txt")]
for file in files:
    with open(os.path.join(path, file), 'r',encoding='utf-8') as f:
        if len(f.readlines())>300:
            os.remove(os.path.join(path,file)) 
Chang
  • 77
  • 6
  • Please provide additional details in your answer. As it's currently written, it's hard to understand your solution. – Community Sep 01 '21 at 19:52
-1

Like Saurabh said, if you wanna do it with Python seems like you'd have to iterate through all the lines in order to count them. This article demonstrates doing it with enumerate(). https://pynative.com/python-count-number-of-lines-in-file/

If you're on Unix you could use AWK since you've already imported os: awk 'END{print NR}' file