簡體   English   中英

在python中打開和讀取文件有什么區別?

[英]What is the difference between opening and reading a file in python?

在python的OS模塊中,有一種打開文件的方法和一種讀取文件的方法。

open方法的文檔說:

打開文件文件,然后根據標志設置各種標志,並根據模式設置可能的模式。 默認模式為0777(八進制),並且當前的umask值首先被屏蔽掉。 返回新打開文件的文件描述符。

read方法的文檔說;

從文件描述符fd讀取最多n個字節。 返回包含讀取的字節的字符串。 如果已到達fd引用的文件末尾,則返回一個空字符串。

我了解從文件中讀取n個字節的含義。 但這與開放有何不同?

“打開”文件實際上並不會將文件中的任何數據帶入程序。 它只是准備要讀取(或寫入)的文件,因此當您的程序准備讀取文件的內容時,它可以立即進行讀取。

打開文件可以讀取或寫入文件(取決於您作為第二個參數傳遞的標志),而實際上讀取文件時會從文件中提取數據,該文件通常保存到變量中進行處理或作為輸出打印。

打開文件后,您並不總是從文件中讀取文件。 打開還允許您通過覆蓋所有內容或附加到內容來寫入文件。

要讀取文件:

>>> myfile = open('foo.txt', 'r')
>>> myfile.read()

首先,您以讀取權限( r )打開文件,然后從文件中read()

寫入文件:

>>> myfile = open('foo.txt', 'r')
>>> myfile.write('I am writing to foo.txt')

每個示例的第1行中唯一要做的就是打開文件。 直到我們實際上從文件中read()到什么都改變

open將為您提供一個fd (文件描述符),稍后您可以從該fd中read

一個人也可以出於其他目的open文件,例如寫入文件。

在我看來,您可以在不調用read方法的情況下從文件句柄讀取行,但是我猜read()確實將數據放在了可變位置。 在我的課程中,我們似乎在不使用read()的情況下打印行,計數行並從行中添加數字。

但是,需要使用rstrip()方法,因為使用for in語句從文件句柄打印行也將在行末打印不可見的換行符,就像print語句一樣。

來自Charles Severance的Python for Everybody,這是入門代碼。

  """
7.2
Write a program that prompts for a file name,
then opens that file and reads through the file,
looking for lines of the form:
X-DSPAM-Confidence:    0.8475
Count these lines and extract the floating point
values from each of the lines and compute the
average of those values and produce an output as
shown below. Do not use the sum() function or a
variable named sum in your solution.
You can download the sample data at
http://www.py4e.com/code3/mbox-short.txt when you
are testing below enter mbox-short.txt as the file name.
"""


# Use the file name mbox-short.txt as the file name

fname = input("Enter file name: ") 
fh = open(fname) 
for line in fh:
    if not line.startswith("X-DSPAM-Confidence:") : 
        continue
    print(line)
print("Done")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM