使用 os.path.join 和 os.path.getsize,返回 FileNotFoundError

Using os.path.join with os.path.getsize, returning FileNotFoundError

结合我的 ,我将打印文件名及其旁边的大小列表。基本上我是从一个文件(由用户添加)中读取文件名,获取文件名并将其放在工作目录的路径中以逐个打印它的大小,但是我遇到以下问题区块:

print("\n--- Stats ---\n")

with open('userdata/addedfiles', 'r') as read_files:
        file_lines = read_files.readlines()

        # get path for each file and find in trackedfiles
        # use path to get size

        print(len(file_lines), "files\n")

        for file_name in file_lines:
        # the actual files should be in the same working directory
            cwd = os.getcwd() 

            fpath = os.path.join(cwd, file_name)
            fsize = os.path.getsize(fpath)

            print(file_name.strip(), "-- size:", fsize)

返回此错误:

tolbiac wpm-public → ./main.py --filestatus

--- Stats ---

1 files

Traceback (most recent call last):
  File "./main.py", line 332, in <module>
    main()
  File "./main.py", line 323, in main
    parseargs()
  File "./main.py", line 317, in parseargs
    tracking()
  File "./main.py", line 204, in tracking
    fsize = os.path.getsize(fpath)
  File "/usr/lib/python3.4/genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: '/home/tolbiac/code/wpm-public/file.txt\n'
tolbiac wpm-public → 

所以看起来有些东西在 file_name 的末尾添加了一个 \n,我不确定这是不是在 getsize 模块中使用的东西,我用 os.stat 试过了,但是它做了同样的事情。

有什么建议吗?谢谢。

当您读入文件时,您需要了解数据是如何分离的。在这种情况下,读入文件每行有一个文件名,由 \n 运算符分隔。在使用之前需要将其剥离。

for file_name in file_lines:
    file_name = file_name.strip()
    # rest of for loop