检查文件是否为空,如果它是f.write它

问题描述:

好吧,所以我基本上是试图f.write一个特定的代码集,如果没有文件已经存在。这是我使用的代码:检查文件是否为空,如果它是f.write它

import sys 
import os 
from string import * 

userType = raw_input("Enter text: ") 

bigtable = '''<html> 
<head> 
<style> 
table, th, td { 
    border: 1px solid black; 
    border-collapse: collapse; 
} 
th, td { 
    padding: 5px; 
    text-align: left;  
} 
</style> 
</head> 
    <body> 
    <table style="width:50%"> 
     <tr> 
      <th>Server</th> 
      <th>Address</th> 
      <th>Name</th> 
      <th>Address2</th> 
     </tr>''' 

if userType == 'file -n' or userType == 'file --nice': 

    with open('Pass.html', 'r') as f: 

     if str(f) != 0 : 
     print('butters') 
     else: 
     f.write(bigtable) 

任何人都可以解释为什么这不工作,如果它可以扫描一个文件,然后写具体信息,成吗?

找到了一种方法,使其与工作:

with open('Pass.html', 'a') as f: 

     if os.path.getsize('C:\Python26\Pass.html') != 0 : 
      print('butters') 
     else: 
      f.write(bigtable) 
+0

一方面,您无法写入您打开阅读的文件。另外,你将一个str()与一个int进行比较。但是,你的意思是“不起作用”? –

+0

不适用于代码本身基本上,为什么我做错了,我假设代码字面上只是错误的事实,我比较字符串与int是一个问题 – Cry2Senpai

一旦你打开了追加模式的文件(如在你的编辑),使用tell()来看看文件是空的(或不存在)之前。