读取日志文件并在其中打开文件 [英] reading logfile and opening files in there

查看:146
本文介绍了读取日志文件并在其中打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读取用另一种方法创建的日志文件时遇到问题. 日志文件中包含解压缩文件的文件路径(解压缩是另一个功能).日志文件看起来像这样

I'm having a problem reading a logfile I'm creating in another method. The logfile has file-paths of unzipped files in it (unpacking is in another function). The logfile looks kinda like this

/home/usr/Downloads/outdir/Code/XXX.something
/home/usr/Downloads/outdir/Code/YYY.something
/home/usr/Downloads/outdir/Code/AAA.something


@staticmethod
def iterate_log(path):
    results = str()
    for dirpath, dirnames, files in os.walk(path):
        for name in files:
            results += '%s\n' % os.path.join(dirpath, name)
    with open(os.path.join(EXTRACT_PATH_, LOGNAME_), 'w') as logfile:
        logfile.write(results)
        return os.path.join(EXTRACT_PATH_, LOGNAME_)

@staticmethod
def read_received_files(from_file):
    with open(from_file, 'r') as data:
        data = data.readlines()
        for lines in data:
        # to reduce confusion I would use
        # for line in data:
            read_files = open(lines)
            print(read_files)
            return read_files

现在,我想逐行读取日志文件(第二种方法中的参数from_files现在是第一种方法的返回值),然后打开这些文件并返回它们(以便在其他地方使用它们). 到目前为止,readlines()read()都给我错误

Now I want to read the logfile line by line (the parameter from_files in the second method is the return value of the first method right now) and open those files and return them (for using them elsewhere). readlines() and read() are both giving me errors so far

readlines() = [Errno2] No sucht file or directory: '/../../../logfile.log\n

read() = IsADirectoryError: [Errno21]

整个回溯:

    Traceback (most recent call last):
  File "files_received_test.py", line 13, in <module>
    main()
  File "files_received_test.py", line 9, in main
    j = Filesystem.execute_code(FILENAME_)
  File "/home/usr/PycharmProjects/Projektgruppe/code/src/filesystem_hasher.py", line 16, in execute_code
    Filesystem.read_received_files(create_log)
  File "/home/usr/PycharmProjects/Projektgruppe/code/src/filesystem_hasher.py", line 54, in read_received_files
    read_files = open(lines)
FileNotFoundError: [Errno 2] No such file or directory: '/home/usr/Downloads/outdir/unpacked_files.log\n'

推荐答案

您只需要删除换行符,然后进行更改

You just need to strip the newline character so change

read_files = open(lines)

read_files = open(lines.strip())

作为观察结果-读取错误消息中的每个字符至关重要-该消息告诉您没有名为

as an observation - critical to read each character in an error message - the message was telling you that there was no file named

'/home/usr/Downloads/outdir/unpacked_files.log\n'

因此很有用然后尝试理解为什么显示\ n的原因-这与您对文件名的期望不符,因此您应该怀疑为什么文件具有该名称

so it is useful to then try to understand why the \n showed up - this did not match your expectation of the file name so you should wonder why the file has that name

这篇关于读取日志文件并在其中打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆