检查文件是否不为空以及文件是否为 f.write
Checking if file is not empty and if it is f.write to it
好的,如果文件中不存在任何内容,我基本上会尝试 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)
一旦您以附加模式打开文件(如在您的编辑中),请使用 tell()
查看文件之前是否为空(或不存在)。
好的,如果文件中不存在任何内容,我基本上会尝试 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)
一旦您以附加模式打开文件(如在您的编辑中),请使用 tell()
查看文件之前是否为空(或不存在)。