python - 在 python 3.4 上逐行读取文本文件

标签 python python-3.x

我将一本书保存为我的 python 上的文本文件,我试图逐行读取该文件。我试过用这个

def print_file1(filename):
    f = open(filename, 't')
    for line in f:
        print(line, end = '')
    f.close() #optional

但是,每次我尝试运行它时,它都不起作用。 这就是我得到的输出

runfile('/Users/kareemahokunlola/example.py', wdir='/Users/kareemahokunlola')

最佳答案

'' 本身不是打开文件的有效模式。

您可以将模式指定为 rt。如果您省略模式,它将默认为 'r'(以文本模式阅读),这可能足以满足您的目的。 (如果您的文件包含二进制数据,您可以将 'b' 添加到模式。)

我也会考虑用 with 语句这样写:

def print_file1(filename):
    with open(filename) as f:
        for line in f:
            print(line, end = '')

这样做的好处是您无需担心关闭文件 - 无论出于何种原因,它都会在 with 语句退出时自动发生。


更新

那么您是从 Spyder IDE 中执行这段代码的吗?当您成功运行脚本时,Spyder 将显示:

runfile('/Users/kareemahokunlola/example.py', wdir='/Users/kareemahokunlola')

in the console. This is what you are seeing, so your script is running without error.

There are a couple of possibile explanations:

  1. You are not calling the function print_file1() from within your script. The script runs without error, but the file is not displayed because print_file1() is not called. This is the most likely explanation because your original code that attempts to open the file with mode 't' will raise an exception, and that exception will be logged to the console. But the error is not displayed, hence it is probable that the function is not actually called.
  2. You are calling print_file1() but the file is empty. In this case the "runfile()" message will be displayed because the script ran successfully, but nothing else is seen because the file is empty.

Try adding a call to print_file1() after you define the function:

def print_file1(filename):
    with open(filename) as f:
        for line in f:
            print(line, end = '')

# N.B. call the function...
print_file1('/etc/hosts')

关于python - 在 python 3.4 上逐行读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33061177/

相关文章:

javascript - 如何在网页中执行 "javascript:__doPostBack"以使用 selenium 下载 pdf 文件?

Python从字典列表列表创建列表

python - 为什么我的 lambda 函数在使用像 filter() 和 map() 这样的函数时不返回任何值?

python - 如何获得不和谐的长度。嵌入 [DISCORD.PY]

python - 无法从登录页面进一步移动,[django-otp]

python - 如何在Python中对itertools石斑鱼数组进行排序

python - 如何在elasticsearch-dsl python中选择特定字段

python - Linux - 存储仅具有用户权限的与用户无关的数据

python Pandas : Getting the locations of a value in dataframe

python - 如何让我的 Vim 和 MacVim 找到 python3?