【问题标题】:Saving data to a file in Python在 Python 中将数据保存到文件中
【发布时间】:2021-07-21 18:56:42
【问题描述】:

我目前正在尝试使用python从一个文件中提取信息,找到我需要的数据,然后将其保存到另一个文件中以备后用。

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()

数据正在保存到列表中(由打印语句检查),但没有保存到文件“commandlist.txt”

关于它为什么不保存的任何想法?它在另一个非常相似的脚本上运行良好

【问题讨论】:

  • 您确定文件在您期望的位置吗?您如何验证文件的内容?你知道当前工作目录是什么吗?
  • @KarlKnechtel 我要保存到的文件与 python 文件位于同一目录中。新文件的内容是空的,因为它是一个输出,我应该验证它吗?
  • 好的,所以你在与python文件相同的目录中有一个空文件。您是否希望脚本尝试写入该文件,而不是写入其他同名文件?如果是这样,为什么?您的计划的哪一部分旨在确保发生这种情况?
  • @PatrickArtner 我不认为这是一个缩进错误。据我了解,他想读取所有文件,并将这些文件中的所有内容添加到badgecommandlist
  • @EdoAkse 是的,我正在尝试打开每个文件,找到包含badge give 等的每一行并将其添加到输出文件中

标签: python python-3.x list file


【解决方案1】:

您的代码存在一些问题。我下面的代码已被注释,应该可以帮助您。

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}')

【讨论】:

    猜你喜欢
    • 2019-09-28
    • 1970-01-01
    • 1970-01-01
    • 2022-10-17
    • 2012-05-07
    • 1970-01-01
    • 2017-09-24
    • 2018-09-11
    • 1970-01-01
    相关资源
    最近更新 更多