4 回答

TA貢獻(xiàn)1859條經(jīng)驗 獲得超6個贊
在嘗試獲取文件大小之前,您沒有關(guān)閉文件,就像在塊內(nèi)所做的那樣。把它帶到外面:with
import os
def create_python_script(filename):
comments = "# Start of a new Python Program"
#filesize = 0
with open(filename, 'w') as new_file:
new_file.write(comments)
cwd=os.getcwd()
fpath = os.path.abspath(filename)
print(fpath)
filesize=os.path.getsize(fpath)
return(filesize)
print(create_python_script('newprogram.py'))
# 31

TA貢獻(xiàn)1853條經(jīng)驗 獲得超18個贊
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, 'w') as file:
file.write(comments)
file.close()
filepath = os.path.abspath(filename)
filesize = os.path.getsize(filepath)
return(filesize)
print(create_python_script("program.py"))
#this will give you correct result

TA貢獻(xiàn)1802條經(jīng)驗 獲得超5個贊
這個也工作得很好!
def create_python_script(filename):
import os
comments = "# Start of a new Python program"
with open(filename,'w')as file:
file.write(comments)
filesize = os.path.getsize(filename)
return(filesize)
print(create_python_script("program.py"))

TA貢獻(xiàn)2019條經(jīng)驗 獲得超9個贊
首先打開具有寫入權(quán)限的文件,以在文件中添加文本。然后以讀取權(quán)限打開文件以獲取文件的大小。
import os
def create_python_script(filename):
comments = "# Start of a new Python program"
with open(filename, 'w') as pd:
pd.write(comments)
with open(filename, "r"):
filesize = os.path.getsize(filename)
print(filesize)
return filesize
print(create_python_script("program.py"))
添加回答
舉報