我想从输入文件中读取特定数据。我怎么读呢?
例如,我的文件包含以下数据:
this is my first line
this is my second line.
所以我只想阅读第一行的first
和第二行的secon
。
答案 0 :(得分:0)
请根据您的需要尝试以下代码,但请阅读上述评论。
# ----------------------------------------
# open text file and write reduced lines
# ----------------------------------------
#this is my first line
#this is my second line.
pathnameIn = "D:/_working"
filenameIn = "foobar.txt"
pathIn = pathnameIn + "/" + filenameIn
pathnameOut = "D:/_working"
filenameOut = "foobar_reduced.txt"
pathOut = pathnameOut + "/" + filenameOut
fileIn = open(pathIn,'r')
fileOut = open(pathOut,'w')
print(fileIn)
print(fileOut)
i = 0
# Save all reduced lines to a file.
for lineIn in fileIn.readlines():
i += 1 # number of lines read
lineOut = lineIn[11:16]
fileOut.writelines(lineOut +"\n")
print("*********************************")
print("gelesene Zeilen: " + str(i))
print("*********************************")
fileIn.close()
fileOut.close()