如果文件为空,如何跳过文件行

2024-05-16

python 3中的程序: 这是我的第一个涉及文件的程序。我需要忽略注释行(以 # 开头)和空行,然后拆分这些行,以便它们可迭代,但我不断收到 IndexError 消息,指出字符串索引超出范围,并且程序在空行处崩溃。

import os.path

def main():

endofprogram = False
try:
    #ask user to enter filenames for input file (which would 
    #be animals.txt) and output file (any name entered by user)
    inputfile = input("Enter name of input file: ")

    ifile = open(inputfile, "r", encoding="utf-8")
#If there is not exception, start reading the input file        
except IOError:
    print("Error opening file - End of program")
    endofprogram = True

else:
    try:     
        #if the filename of output file exists then ask user to 
        #enter filename again. Keep asking until the user enters 
        #a name that does not exist in the directory        
        outputfile = input("Enter name of output file: ")
        while os.path.isfile(outputfile):
            if True:
                outputfile = input("File Exists. Enter name again: ")        
        ofile = open(outputfile, "w")

        #Open input and output files. If exception occurs in opening files in 
        #read or write mode then catch and report exception and 
        #exit the program
    except IOError:
        print("Error opening file - End of program")
        endofprogram = True            

if endofprogram == False:
    for line in ifile:
        #Process the file and write the result to display and to the output file
        line = line.strip()
        if line[0] != "#" and line != None:
            data = line.split(",")
            print(data)                
ifile.close()
ofile.close()
main() # Call the main to execute the solution

你的问题来自于空行不是这样的事实None,正如您似乎假设的那样。以下是可能的修复:

for line in ifile:
    line = line.strip()
    if not line:  # line is blank
        continue
    if line.startswith("#"):  # comment line
        continue
    data = line.split(',')
    # do stuff with data
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果文件为空,如何跳过文件行 的相关文章

随机推荐

  • 使用 BitmapEncoder 生成时如何使 GIF 循环重复

    我能够使用 BitmapEncoder C WinRT 创建动画 gif 但是 我一直无法弄清楚如何让GIF循环回来并从头开始 没有尝试太多 因为我不确定要尝试什么 搜索了更多要在 GIF 上设置的属性 但找不到任何相关内容 好吧 终于能弄
  • 为具有多个目标和不同平台的项目编写 Podfile

    我正在准备一个支持 OS X 和 iOS 的 Pod 我的 pod 有一些自己的依赖项 这些依赖项在 podspec 文件中定义 因此我使用 Podfile 来管理我用来开发 pod 和运行测试的项目的依赖项 我正在使用 CocoaPods
  • 将 sensu-client 连接到服务器时 AMQP 连接的 bad_header

    我已经安装了 sensu 和厨师社区食谱 但是 sensu客户端无法连接到服务器 导致rabbitmq连接错误 尝试连接时消息超时 这是详细的客户端日志 来自 sensu client log 的日志 timestamp 2014 07 0
  • console.log 未显示正确的值[重复]

    这个问题在这里已经有答案了 我正在尝试控制台一个对象 尽管它没有抛出任何错误 但我想要的结果在一段时间后显示 但我无法检索它 它显示一个 i 图标 上面写着 刚刚评估了下面的值 但我无法获取该值 OUTPUT Promise state s
  • 在 Python 中替换三元运算符的最佳方法是什么? [复制]

    这个问题在这里已经有答案了 可能的重复 Python 中的三元条件运算符 https stackoverflow com questions 394809 ternary conditional operator in python 如果我
  • jQuery 动画延迟

    如何使用 jQuery 延迟动画 我需要获得一个导航来扩大宽度 然后扩大高度 然后反转以获得反向动画 Code function nav li not logo nav li ul li hover function this animat
  • NHibernate 获取 & 字符串 Id

    我在 NHibernate 上有一个分配了字符串 Id 的实体 并且在通过 Id 获取实体时遇到了一些问题 例子 假设有这样的数据库记录 Id Description AAA MyDescription 现在 如果我使用搜索 ID aaa
  • 如何在 https 连接上检索 cookie?

    我试图将 cookie 保存在使用 SSL 但始终返回 NULL 的 URL 中 private Map
  • Firebase 身份验证无法启用 Google 身份验证方法 - “更新 Google 时出错”

    我正在尝试使用 Google Auth 登录方法启用 Firebase 身份验证 但启用它并单击 保存 显示错误 更新 Google 时出错 https i stack imgur com HMVGD png 在 Google Cloud
  • 为什么总是./configure;制作;进行安装;作为 3 个单独的步骤?

    每次从源代码编译某些内容时 都会经历相同的 3 个步骤 configure make make install 我明白 将安装过程分为不同的步骤是有意义的 但我不明白 为什么这个星球上的每个编码员都必须一次又一次地编写相同的三个命令才能完成
  • 全局变量声明

    我是 Python 的初学者 并且已经处理过全局变量的概念 当我以为我理解了这个概念时 我看到了一段简短的代码 证明我错了 message global def enclosure message enclosure def local g
  • ::after 内联 HTML 电子邮件?

    banner width 34px height 52px position relative color white font size 11px letter spacing 0 2em text align center float
  • 主题以编程方式设置。如何重新加载 Activity 来应用

    如何在不重新启动整个应用程序的情况下应用主题 如果我这样做startActivity getIntent finish 活动退出并且不重新启动 是否可以简单地重新启动 重新创建活动来应用主题 它的顺序不正确 finish intent ne
  • 针对特定值的 Linq OrderBy

    Linq 中是否有一种方法可以在不知道值的顺序的情况下对一组值 在本例中为字符串 执行 OrderBy 考虑这个数据 A B A C B C D E 以及这些变量 字符串第一优先 第二优先 第三优先 当值设置如下时 firstPref A
  • 如何正确地将 Facebook JavaScript SDK 注入 AngularJS 控制器?

    我是 AnuglarJS 的新手 并且已经用它构建了一个小型网络应用程序 我想将 Facebook JavaScript SDK 与它一起使用 但使用最佳实践 依赖项注入控制器 以维护应用程序结构和可测试性 我找到了这个https grou
  • Play 框架:从 Build.sbt 读取版本

    我看到了很多关于如何从 build sbt 读取版本的问题 并且已经提供了很多解决方法来解决如何将 build sbt 指向 conf application conf 并在中指定版本改为conf application conf 我有一个
  • 将roottools.jar导入Android Studio

    我正在尝试从这里导入 roottools https code google com p roottools https code google com p roottools jar 文件 到 Android Studio 项目 到目前为
  • 将 Dropout 与 Keras 和 LSTM/GRU 单元结合使用

    在 Keras 中 您可以像这样指定 dropout 层 model add Dropout 0 5 但对于 GRU 单元 您可以将 dropout 指定为构造函数中的参数 model add GRU units 512 return se
  • 序列化表达式树

    我正在用 C 做一个分布式系统 并且遇到了障碍 我需要能够使用类型序列化谓词 Predicate
  • 如果文件为空,如何跳过文件行

    python 3中的程序 这是我的第一个涉及文件的程序 我需要忽略注释行 以 开头 和空行 然后拆分这些行 以便它们可迭代 但我不断收到 IndexError 消息 指出字符串索引超出范围 并且程序在空行处崩溃 import os path