[英]Python file-io code listing current folder path instead of the specified
[英]Basic python file-io variables with enumerate
python的新手,並試圖學習文件i / o的繩索。
我正在使用以下格式從大型(200萬行)文件中提取行:
56fr4
4543d
4343d
5irh3
這是我用來返回代碼的函數:
def getCode(i):
with open("test.txt") as f:
for index, line in enumerate(f):
if index == i:
code = # what does it equal?
break
return code
一旦索引到達正確的位置(i),我使用什么語法來設置代碼變量?
code = line.strip()
將刪除尾隨的新行時,將代碼分配給等於i的行號。
您還需要稍微更新您的代碼
def getCode(i):
with open('temp.txt', 'r') as f:
for index, line in enumerate(f):
if index == i:
code = line.strip()
return code
為什么你需要.strip()
>>> def getCode(i):
... with open('temp.txt') as f:
... for index, line in enumerate(f):
... if index == i:
... code = line
... return code
...
>>> getCode(2)
" 'LINGUISTIC AFFILIATION',\n"
是的,“'LINGUISTIC AFFILIATION',”是我目前的temp.txt'
enumerate
將一個迭代器轉換為另一個迭代器,這樣你迭代的東西就成了一對(數字ID,來自底層迭代器的原始項)。
在我們的情況下:
for index, line in enumerate(f):
f
是文件對象。 文件對象是迭代器:它們遍歷文件的行。
我們將它轉換為迭代器(行號,行文件)對。
for
循環語法遍歷迭代器,並將(行號,文件行)對分配給變量:(index,line)。 這只是將一個元組分配給另一個元組的正常行為。
因此,每次循環時,都會為index
分配一個行號,並從該文件中為line
分配相應的行。 文件中的行是你想要的(可能有一些格式), line
包含它,所以......
如果上述任何一個沒有意義,您可能需要重新閱讀該語言的介紹。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.