4 回答
TA贡献1859条经验 获得超6个赞
在尝试获取文件大小之前,您没有关闭文件,就像在块内所做的那样。把它带到外面: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贡献1853条经验 获得超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贡献1802条经验 获得超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贡献2019条经验 获得超9个赞
首先打开具有写入权限的文件,以在文件中添加文本。然后以读取权限打开文件以获取文件的大小。
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"))
添加回答
举报