1
0

convert.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. import csv
  2. import os
  3. # Create folders for each first digit of IP address
  4. for i in range(256):
  5. folder_path = f"geoip/{i}"
  6. if not os.path.exists(folder_path):
  7. os.makedirs(folder_path)
  8. # Read CSV file and create text files
  9. with open('geoipv4.csv', 'r') as csvfile:
  10. csvreader = csv.reader(csvfile)
  11. for row in csvreader:
  12. start_ip = row[0]
  13. end_ip = row[1]
  14. country = row[2]
  15. first_digit, second_digit, _, _ = start_ip.split(".")
  16. file_path = f"geoip/{first_digit}/{second_digit}.txt"
  17. if os.path.exists(file_path):
  18. append_write = 'a' # append if already exists
  19. else:
  20. append_write = 'w' # make a new file if not
  21. with open(file_path, append_write) as file:
  22. file.write(f"{start_ip},{end_ip},{country}\n")
  23. # Clean empty folders
  24. root_dir = "geoip/"
  25. # Loop through all subdirectories in the root directory
  26. for subdir in os.listdir(root_dir):
  27. subdir_path = os.path.join(root_dir, subdir)
  28. # Check if the subdirectory contains any txt files
  29. if not any(fname.endswith(".txt") for fname in os.listdir(subdir_path)):
  30. # If not, remove the subdirectory
  31. os.rmdir(subdir_path)