简体   繁体   English

Python不在for循环中打印文件内容

[英]Python not printing file contents in for loop

I have this code below:我在下面有这个代码:

import os

dir = os.listdir('files/')

for file in dir:
    print(file)

    with open(file, 'r') as f:
        x = f.readlines()
        print(x)

Whenever I run it I get the following output:每当我运行它时,我都会得到以下输出:

TextFile1.txt
[]
TextFile2.txt
[]

In the 2nd and 4th line it is printing out an empty array even though the file has contents.在第 2 行和第 4 行中,即使文件有内容,它也会打印出一个空数组。

TextFile1.txt contains: TextFile1.txt 包含:

code 1
email 1
pw 1

and TextFile2.txt contains:和 TextFile2.txt 包含:

code 2
email 2
password 2

I'm not sure why it's printing as an empty array when the file isn't empty, any help would be appreciated.我不确定为什么当文件不为空时它会打印为空数组,任何帮助将不胜感激。

os.listdir only returns the file names and not the full path to those files, you need to join the directory name and the file name before opening os.listdir只返回文件名而不是这些文件的完整路径,您需要在打开之前加入目录名和文件名

import os

BASE_DIR = 'files/'
dir = os.listdir(BASE_DIR)

for file in dir:
    print(file)

    with open(os.path.join(BASE_DIR, file), 'r') as f:
        x = f.readlines()
        print(x)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM