【发布时间】:2014-07-19 02:35:22
【问题描述】:
在我的程序中,我打开一个用户输入其名称的文件,计划读取并附加该文件 (a+)。我使用 seek(0) 将指针移动到文件的开头,因为使用 a+ 时它从文件末尾开始。然后我使用 readline() 函数,并检查程序从行中读取的内容是否在元组中。代码如下:
fileName = input()
fileName += ".txt"
file = open(fileName, "a+")
fileName += ","
print("Opened", fileName, "reading:")
print()
#Reading operation selection
file.seek(0)
operation = file.readline() #Line 0 = operation
if operation not in ('+', '-', '*', '/'):
print("Did not find valid operation in file.")
print("Use a file with valid calculation code:")
continue
我有一个文本文件“file.txt”,其中包含以下内容:
+
12
12
c
当我运行程序并输入'file'时,它返回'Opened file.txt,阅读:在文件中找不到有效操作。使用具有有效计算代码的文件:'。 所以,我在一个单独的文件中进行了故障排除并运行了以下代码:
fileName = input()
fileName += ".txt"
file = open(fileName, "a+")
fileName += ","
print("Opened", fileName, "reading:")
print()
#Reading operation selection
file.seek(0)
operation = file.readline() #Line 0 = operation
print(operation)
if operation not in ('+', '-', '*', '/'):
print("Did not find valid operation in file.")
print("Use a file with valid calculation code:")
continue
我运行了这个程序,输入'file'作为文件名,它返回: 打开file.txt,阅读:
+
Did not find valid operation in file.
Use a file with valid calculation code:
为什么变量操作包含file.txt第一行的单个字符,后面是一个空行?
感谢任何帮助,谢谢!
【问题讨论】: