简体   繁体   English

Python read() 不读取文件

[英]Python read() doesn't read the file

So I made a simple script in Python which takes a filename as a command line argument and reads the given file whenever the script is executed.所以我用 Python 制作了一个简单的脚本,它将文件名作为命令行参数,并在执行脚本时读取给定的文件。 Pretty straight forward, whenever I execute the script it does not print the text inside the file, nor do I get an error.非常简单,每当我执行脚本时,它不会打印文件内的文本,也不会出现错误。 I am pretty new to programming and have been breaking my head for hours in this piece of code.我对编程很陌生,并且在这段代码中已经让我头疼了好几个小时。

import sys

def openfile(filename):
    f = open(filename, mode='r')
    f.read()
    f.close()

if __name__ == '__main__':
        openfile(filename = sys.argv[1])
        print('script has been executed')

Quick disclaimer I know someone posted a similar question a few years ago, but he did not get a direct answer on why his code wasn't working and I did not get the information I was looking out for the answers.快速免责声明我知道几年前有人发布了类似的问题,但他没有直接回答为什么他的代码不起作用,我也没有得到我正在寻找答案的信息。 Also sorry for my poor English.也为我糟糕的英语感到抱歉。 I did my best to keep it clear, but English is not my first language.我尽力保持清楚,但英语不是我的第一语言。

You are reading the file f.read() but you need to assign the content to a variable or print it or something.您正在阅读文件f.read()但您需要将内容分配给变量或打印它或其他内容。 Python won't print the content of every file you read just because you read it: you have to tell it what to do with the result. Python 不会仅仅因为你读过它就打印你读过的每个文件的内容:你必须告诉它如何处理结果。

For python newbie, studying the Python anti-patterns is a must.对于 Python 新手来说,学习Python 反模式是必须的。 This allow one avoid many mistake and bugs.这可以避免许多错误和错误。 OP apparently has pass experience from other programming language but doesn't aware of better way of working in python. OP 显然拥有其他编程语言的通过经验,但不知道在 python 中更好的工作方式。

If you study the anti-pattern, you will learn with open() is the better way to open a file.如果您研究了反模式,您将了解到with open()是打开文件的更好方法。 Immediately, you will spot f as a file handler, which will not store any data unless you pass data from f.read() function to another variable.立即,您会发现f是一个文件处理程序,它不会存储任何数据,除非您将数据从f.read()函数传递给另一个变量。

def openfile(filename):
    with open(filename) as f:
        data = f.read()
    # to print out the contents
    print(data)

Using sys.argv is acceptable, but argparse is highly recommended.使用 sys.argv 是可以接受的,但强烈建议使用argparse

It appears as though the program simply reads the file that is passed into the command line argument.程序似乎只是读取传递给命令行参数的文件。 The program functions and reads the file, but you need a line to tell python to print the contents of the file you are reading.该程序运行并读取文件,但您需要一行来告诉 python 打印您正在读取的文件的内容。 Try this:尝试这个:

import sys

def openfile(filename):
    f = open(filename, mode='r')
    contents = f.read()
    print(contents)
    f.close()

if __name__ == '__main__':
    openfile(filename=sys.argv[1])
    print('script has been executed')

You are reading the file but you have to assign the contents to some variable or you can just print the contents.您正在阅读文件,但您必须将内容分配给某个变量,或者您可以只打印内容。

For Example:例如:

f = open("SampleTextFile_100kb.txt", "rt") here r for read and t for text file f = open("SampleTextFile_100kb.txt", "rt")这里r用于读取, t用于文本文件

print(f.read()) # TO READ AND PRINT COMPLETE FILE. print(f.read()) # 读取并打印完整的文件。

print(f.read(55)) # TO READ UPTO SPECIFIED CHARACTERS LIMIT. print(f.read(55)) # 读取最多指定的字符限制。

TO READ LINE/S OR THE WHOLE FILE AS LINES:将行/S 或整个文件作为行阅读:

print(f.readline()) #TO READ MULTIPLE LINES print(f.readline()) print(f.readline())

TO READ THE WHOLE FILE AS LINES将整个文件作为行阅读

for x in f:
print(x)

hope this helps.希望这可以帮助。

I strongly recommend @mootmoot 's approach with the context manager.我强烈推荐 @mootmoot 使用上下文管理器的方法。 This is not only easier to read, but it also catches exceptions when the file cannot be read for some reason.这不仅更易于阅读,而且在由于某种原因无法读取文件时也能捕获异常。 If you don't want to use a context manager, I would suggest you use the try-except commands to for your function.如果您不想使用上下文管理器,我建议您使用 try-except 命令来处理您的功能。 It is unsafe if you do it like @Adam Merki suggested because there will be no guarantee that the file will be closed if an exception occurs while reading the file.如果你像@Adam Merki 建议的那样做是不安全的,因为如果在读取文件时发生异常,将无法保证文件将被关闭。

Using try-except statements, your function could look like this:使用 try-except 语句,您的函数可能如下所示:

import sys

def openfile(filename):

    f = open(filename, mode='r')
    try:
        print(f.read())

    except:
        print('something went wrong')

    else:
        print('nothing went wrong')

    finally:
        f.close()


if __name__ == '__main__':
    openfile(filename=sys.argv[1])
    print('script has been executed')

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

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