reading logfile and opening files in there

余生颓废 提交于 2019-12-25 06:44:18

问题


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:


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



来源:https://stackoverflow.com/questions/35971854/reading-logfile-and-opening-files-in-there

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!