0

I am currently trying to use python to extract information from one file, find the data that I need then save it to another file for later use.

badgecommandlist = []
directory = "D:\Python\Badge Recovery"
for filename in os.listdir(directory): #open each file
   newname = directory + "/" +  filename
   print(filename)
   f=open(newname, "r")
   lines = f.readlines() #read content of each file
   f.close()
   
   for line in lines:
      if "badge give" in line or "badge share" in line or "badge take" in line or "badge leave" in line or "badge create" in line: #check if badge command is in each line
         badgecommandlist.append(line)
print(badgecommandlist)
f=open("commandlist.txt", "w")
for line in badgecommandlist:
   f.writelines(line)
f.close()

The data is being saved into the list (checked by the print statement) but it isn't being saved to the file "commandlist.txt"

Any ideas on why it isnt saving? It worked fine on another script that was very similar

Zenot1c
  • 25
  • 5
  • Are you sure the file is in the place where you expect it to be? How are you verifying the contents of the file? Do you know what a *current working directory* is? – Karl Knechtel Jul 21 '21 at 19:10
  • @KarlKnechtel the file I am trying to save to is in the same directory as the python file. The contents of the new file is empty as it is an output, should I be verifying it? – Zenot1c Jul 21 '21 at 19:12
  • 2
    Okay, so you have an empty file in the same directory as the python file. Do you expect the script to try to write to that file, instead of to a file somewhere else with the same name? If so, *why*? What part of your program is intended to make sure that happens? – Karl Knechtel Jul 21 '21 at 19:14
  • 1
    @PatrickArtner I don't think that's an indentation error. From what I understand, he wants to read all files, and add everything in these files to `badgecommandlist` – Edo Akse Jul 21 '21 at 19:24
  • @EdoAkse yes, I am trying to open each file, find every line that contains ```badge give``` ect and add it into the output file – Zenot1c Jul 22 '21 at 16:30
  • So what happens if you run the code in my answer? – Edo Akse Jul 22 '21 at 17:13

1 Answers1

0

Some issues with your code. My code below is commented and should get you going.

import os
from pprint import pprint


def get_files_from_path(path: str = ".", ext=None) -> list:
    """Find files in path and return them as a list.
    Gets all files in folders and subfolders

    See the answer on the link below for a ridiculously
    complete answer for this. I tend to use this one.
    note that it also goes into subdirs of the path
    https://stackoverflow.com/a/41447012/9267296
    Args:
        path (str, optional): Which path to start on.
                              Defaults to '.'.
        ext (str/list, optional): Optional file extention.
                                  Defaults to None.

    Returns:
        list: list of full file paths
    """
    result = []
    for subdir, dirs, files in os.walk(path):
        for fname in files:
            # use os.sep to get os independent separator
            filepath = f'{subdir}{os.sep}{fname}'
            if ext == None:
                result.append(filepath)
            elif type(ext) == str and fname.lower().endswith(ext.lower()):
                result.append(filepath)
            elif type(ext) == list:
                for item in ext:
                    if fname.lower().endswith(item.lower()):
                        result.append(filepath)
    return result


directory = "D:\Python\Badge Recovery"
filelist = get_files_from_path(directory)


badgecommandlist = []
for filename in filelist:
    print(f'Reading file: {filename}')
    # I always use the with open way as it automagically closes the file
    with open(filename) as infile:
        lines = infile.readlines()  # read content of each file

    for line in lines:
        if (
            "badge give" in line
            or "badge share" in line
            or "badge take" in line
            or "badge leave" in line
            or "badge create" in line
        ):  # check if badge command is in each line
            badgecommandlist.append(line)


pprint(badgecommandlist)
with open("commandlist.txt", "w") as outfile:
    # no need to write line by line as writelines()
    # accepts a list directly
    outfile.writelines(badgecommandlist)
    print(f'File saved to: {outfile.name}')
Edo Akse
  • 4,051
  • 2
  • 10
  • 21