簡體   English   中英

在Python中閱讀與打開

[英]Reading versus Opening in Python

為了完成任務,我創建了一段代碼。 目的是打開一個文件,並查找來自發件人的電子郵件地址。

#open file
fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)


#look for the appropriate lines and add the in a list
names = []
for line in fh:
    line = line.rstrip()
    if line.startswith("From:"):
        words = line.split()
        names.append(words[1])

我的問題是:為什么

fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)


#look for the appropriate lines and add the in a list
names = []
for line in fh:
line = line.rstrip()
    if line.startswith("From:"):
        words = line.split()
        names.append(words[1])

工作但是

fname = raw_input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"

fh = open(fname)
text = read.fh()


#look for the appropriate lines and add the in a list
names = []
for line in text:
line = line.rstrip()
    if line.startswith("From:"):
        words = line.split()
        names.append(words[1])

慣於?

我很難理解為什么我應該只使用open而不閱讀。

謝謝

首先,你需要更換, read.fh()fh.read()因為read尚未確定和fh是你想從中讀取數據的文件對象。

其次,問題是fh.read()返回一個字符串,而不是行列表。 因此,當您遍歷時,您是按角色進行的。 這不是您想要的。

如果要使用fh.read(),則必須按行分割text 因此,請在for循環中使用text.split('\\n')代替文本。

暫無
暫無

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

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