有谁知道为什么写这个.txt文件不起作用?

时间:2016-04-08 16:12:46

标签: python text-files

当我运行此代码并为cropquantity输入值时,它不会像crop database.txt那样将它们写入crop database.txt,而只是创建crop = input("Which crop? ") quantity = input("How many? ") with open ('cropdatabase.txt', 'a+') as file: lines = file.readlines() file.close () with open ('cropdatabase.txt', 'a+') as file: for row in lines: if crop in row: row = str(a) split_2 = a.split (',') split_2.append (quantity) else: file.write ('\n') file.write (crop + ' ') file.write (quantity + ' ') file.close () 作为新的空白文本文件。有人知道为什么吗?是因为我关闭文件的方式吗?

Private Sub button1_click()
Dim inRng As Range, outRng As Range

inSelect:
Set inRng = Application.InputBox("Select Range to Calculate", Type:=8)
    If inRng.Cells.Count <> 8 Then
        MsgBox "Select a range with 8 cells!", vbCritical
        GoTo inSelect
    End If
outSelect:
Set outRng = Application.InputBox("Select Cell to Output To", Type:=8)
    If outRng.Cells.Count > 1 Then
        MsgBox "Select only one cell!", vbCritical
        GoTo outSelect
    End If

outRng.Value = VanillaCall(inRng.Cells(1), inRng.Cells(2), inRng.Cells(3), inRng.Cells(4), inRng.Cells(5), inRng.Cells(6), inRng.Cells(7), inRng.Cells(8))

End Sub

4 个答案:

答案 0 :(得分:1)

如果您以空文件(或不存在)开头,则列表lines将为空。因此,编写任何内容的代码都不会运行。

答案 1 :(得分:0)

哈哈哈小虫子。

  • 使用open(filename,'r')来读取文件
  • 使用open(filename,'a')将一些数据附加到现有文件
  • 使用open(filename,'w')创建/重写文件。

当你打开附加'a'的文件时,说明文件指针放在EOF(文件结束)指针之前。所以你不会读任何数据。

我更喜欢使用'a +',它看起来很棒,但使用特定格式可以更清晰地阅读代码。

试试这个

with open ('cropdatabase.txt', 'r') as file:

   lines = file.readlines()

希望这有帮助。

答案 2 :(得分:0)

以下是您的评论代码:

crop = input("Which crop? ")
quantity = input("How many? ")

如果您使用的是python 2,这是一个坏主意。使用raw_input

with open ('cropdatabase.txt', 'a+') as file:

您正在打开此文件以追加,但只是阅读

 lines = file.readlines()

file.close ()

由于您使用'with open'

,因此无需关闭
with open ('cropdatabase.txt', 'a+') as file:

再一次打开追加。你应该用'w'重写文件

 for row in lines:

    if crop in row:

       row = str(a)
       split_2 = a.split (',')
       split_2.append (quantity)

这对我没有意义。什么是?
在与split2混淆之后(再次,为什么)你永远不会写任何东西

    else:

       file.write ('\n')
       file.write (crop + ' ')
       file.write (quantity + ' ')

现在您将裁剪和数量写入没有匹配的行吗?

file.close ()

再次,不必要的关闭

这是我的代码

crop = raw_input("Which crop? ")
quantity = raw_input("How many? ")

使用raw_input,两者都是字符串

with open ('cropdatabase.txt', 'r') as file:
    lines = file.readlines()

将完整文件读入行,然后将其关闭(自动)

with open ('cropdatabase.txt', 'w') as file:
    for row in lines:
        if crop in row:
            row = row.strip(), ", ", quantity
            file.write(row)

您没有指定,因此我正在编写与crop匹配的行并在逗号后添加数量

        else:
            file.write(row)

试试这个,然后回头看看你看到的内容。首先将输入文件保存为其他名称,以便比较两个

答案 3 :(得分:-1)

首先你需要使用raw_input

crop = raw_input("Which crop? ")
quantity = raw_input("How many? ")

然后你不需要f.close(),因为你已经打开了。

相关问题