[英]How do i read a specific line of text from a file and use it as a parameter for a function
我正在編寫一個 Python 腳本 (2.7),它將從文本文件中獲取一行文本並將其用作函數的參數,但我似乎無法弄清楚如何將該行作為函數的參數傳遞我還想知道如何修改文件中已經存在的行而不使用 Python 中的文本編輯器打開它
#!/usr/bin/python
data = open("/tmp/INFO.txt", 'r')
Line = data.readlines()[2]
print Line
要獲取特定行:
f = open("yourFile.txt", "r")
line = f.readlines()[yourLineNumber]
f.close()
將其作為參數傳遞:
yourFunction(line)
要讀取特定行並將其用作參數,您首先需要打開文件然后讀取內容。
with open(filePath, 'r') as fd:
fileContents = fd.readlines()
然后你可以調用fileContents[n]
,其中 n 是你需要的行的索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.