reading logfile and opening files in there

2019-09-03 09:45发布

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

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]

whole traceback:

    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'

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-09-03 10:00

You just need to strip the newline character so change

read_files = open(lines)

to

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'

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

查看更多
登录 后发表回答