所以即時通訊嘗試獲取python中.txt文件中的行數。我的文件有62行,但是我的程序告訴我,它有184行。試圖在Python中獲取.txt的大小
import os
lines = os.path.getsize("file.txt")
print lines
我做錯了什麼?
所以即時通訊嘗試獲取python中.txt文件中的行數。我的文件有62行,但是我的程序告訴我,它有184行。試圖在Python中獲取.txt的大小
import os
lines = os.path.getsize("file.txt")
print lines
我做錯了什麼?
你應該做這種方式,如果要計算行數:在你的代碼,你正在閱讀您的文件的大小以字節爲單位
def wc(filename):
"""
counts # of lines in a file (Like UNIX's [wc -l])
"""
with open(filename, 'r') as f:
return sum(1 for l in f)
lines = wc('file.txt')
由於documentation狀態:
os.path.getsize(path)
返回的大小,以字節爲單位的路徑。如果文件不存在或無法訪問,請提高OSError。
使用不同的方法,如打開文件並遍歷它:
with open('file.txt') as f:
print sum(1 for line in f)
如果您使用的是Mac OSX或Linux,並根據你的目的,它可能對你更簡單打開您的終端並鍵入:
wc -l "filename"
wc是字數,加上-l將其更改爲行數。
您是否閱讀過['os.path.getsize()'](https://docs.python.org/2/library/os.path.html#os.path.getsize)的文檔? –
你爲什麼認爲'getsize'會是一個行數?! – jonrsharpe