【问题标题】:Checking if file is not empty and if it is f.write to it检查文件是否不为空以及是否为 f.write
【发布时间】:2017-10-09 18:17:07
【问题描述】:

好的,所以如果文件中不存在任何内容,我基本上是在尝试编写一组特定的代码。这是我正在使用的代码:

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)

【问题讨论】:

  • 一方面,您无法写入您打开读取的文件。此外,您将 str() 与 int 进行比较。但是“不起作用”是什么意思?
  • 不适用于代码本身,基本上为什么我做错了什么,我假设代码实际上只是错误的事实,即我将字符串与字符串进行比较int 是个问题

标签: string if-statement fwrite python-2.6


【解决方案1】:

以追加模式打开文件后(如在编辑中),使用 tell() 查看文件之前是否为空(或不存在)。

【讨论】:

    猜你喜欢
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2023-02-16
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多