Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中读取和写入文件_Python_File - Fatal编程技术网

在Python3中读取和写入文件

在Python3中读取和写入文件,python,file,Python,File,我一直在做这个与文件有关的程序,已经有很长时间了。我有一个文件: import os.path endofprogram=False try: filename1=input("Enter input file: ") filename2=input("Enter output file: ") while os.path.isfile(filename2): filename2=input("File Exists! Enter new name for

我一直在做这个与文件有关的程序,已经有很长时间了。我有一个文件:

import os.path

endofprogram=False
try:

   filename1=input("Enter input file: ")
   filename2=input("Enter output file: ")

   while os.path.isfile(filename2):
       filename2=input("File Exists! Enter new name for output file: ") 

except IOError:
   print("Error opening file - End of program")
   endofprogram=True

if(endofprogram == False):
   infile=open(filename1, "r")
   content=infile.read()
   lines=[]
   words=[]

   lines=content.split('\n')
   print("Total animals=",len(lines))  
我应该回答以下问题:

  • 动物总数
  • 危险动物总数
  • 安全的大型动物数量

到目前为止,我可以打印出动物总数,但它包括空白空间和注释线,我不想要。目前,对于动物总数来说,打印出来的是19只,而应该是16只。我不知道从那之后的两个问题开始。与其一次读取全部内容,然后拆分
内容,不如对文件对象使用readlines()方法,如下所示:

#color     size    flesh     class
brown     large    hard      safe
green     large    hard      safe
red       large    soft      dangerous
green     large    soft      safe


red       small    hard      safe
red       small    hard      safe
brown     small    hard      safe
green     small    soft      dangerous
green     small    hard      dangerous
red       large    hard      safe
brown     large    soft      safe
green     small    soft      dangerous
red       small    soft      safe
red       large    hard      dangerous
red       small    hard      safe
green     small    hard      dangerous 
然后,您可以进行一些筛选,在解析列之前删除注释行和/或空行

例如,如果len(line.strip())>0,则列表理解
lines=[line for line-in-line]。您可以做一些类似的事情来删除注释行


split
方法更适合实际解析每一行。

您应该逐行处理文件,这比读取整个文件更容易,例如:

lines = infile.readlines()

下面是一个相当冗长的方法:

infile = open('entrada', 'r')

animals = 0
safe_animals = 0
dangerous_animals = 0

for line in infile:
    line_components = line.strip().split()
    if line_components:
        animals += 1

        if line_components[3] == 'dangerous':
            dangerous_animals += 1
        elif line_components[3] == 'safe' and line_components[1] == 'large':
            safe_animals += 1

print "%i animals" % animals
print "%i safe animals" % safe_animals
print "%i dangerous animals" % dangerous_animals

说明:迭代所有行。如果该行为空或为注释,请跳过它。否则,拆分该行并将其添加到所有动物。每个动物都是一个由四个元素组成的列表(因此列索引位于第一行)。现在只需对匹配的动物进行筛选和计数。

为什么不使用数据库、yaml或json保存数据

比纯文本文件好得多,更容易解析/查询

json
Pyaml

请修复缺失的冒号和缩进。哎呀,对不起!已修复。@lfhfsfhjsf使用操作系统提供的可用错误,而不是定义自己的程序结束和错误。熟悉使用std err,并尝试捕获异常。”代码'try:etc等等然后除了OSError作为e:print>>sys.stderr,“执行失败:”,eThank you,您是否可以帮助我完成问题的其他部分?我必须找到危险动物的总数和安全动物的数量。对不起,这不是我的意思。我想说的是,我必须找到危险动物的数量和安全的大型动物的数量。好的,你在
行组件
列表中有每种动物的所有信息,因此你可以很容易地检查它是否大型和安全。不过我刚刚编辑了代码。谢谢你的帮助:)这意味着很多。你能把这个标记为问题的答案吗?它是左边分数下面的记号符号。
color, size, flesh, clas = 0, 1, 2, 3 #column index
animals = []
with open ('animals.txt') as f:
    for line in f:
        if line[0] in '#\n': continue
        animals.append(line.split())
print(animals)
print(len(animals))
print(sum(1 for animal in animals if animal[clas] == 'dangerous'))
print(sum(1 for animal in animals if animal[clas] == 'safe' and animal[size] == 'large'))