2017-10-09 70 views
0

好吧,所以我基本上是試圖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

回答

1

一旦你打開了追加模式的文件(如在你的編輯),使用tell()來看看文件是空的(或不存在)之前。