Python 我正在尝试制作一个程序,该程序写入一个文件,然后查找该文件中写入的内容
这段代码不起作用,它显示find()需要一个参数,而0是在我清楚地说明了一个在Python中是(“Hello”)时给出的:Python 我正在尝试制作一个程序,该程序写入一个文件,然后查找该文件中写入的内容,python,Python,这段代码不起作用,它显示find()需要一个参数,而0是在我清楚地说明了一个在Python中是(“Hello”)时给出的: a=("Hello") f = open("hello.csv","a") f.write(a) g=str.find(a) if g== (True): print("True") f.close() 相当于 Class.method(instance) str是一个类,因此str.find(a)相当于a.find(),它显然缺少要找
a=("Hello")
f = open("hello.csv","a")
f.write(a)
g=str.find(a)
if g== (True):
print("True")
f.close()
相当于
Class.method(instance)
str
是一个类,因此str.find(a)
相当于a.find()
,它显然缺少要找到的第二个字符串:
instance.method()
>“你好”。查找()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
“你好”
TypeError:find/rfind/index/rindex()至少接受1个参数(给定0个)
>>>str.find(“你好”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
str.find(“你好”)
TypeError:find/rfind/index/rindex()至少接受1个参数(给定0个)
>>>“你好”。查找(“e”)
1.
>>>str.find(“你好”,“e”)
1.
您需要指定两个字符串——一个要查找,一个要查找,可以是look\u-in.find(to\u-find)
,或者str.find(look\u-in,to\u-find)
(前者更常规,可读性更好)
另外,如果g==(True):,您应该简单地编写
如果g:
。看看。试着这样做:
>>> "hello".find()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
"hello".find()
TypeError: find/rfind/index/rindex() takes at least 1 argument (0 given)
>>> str.find("hello")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
str.find("hello")
TypeError: find/rfind/index/rindex() takes at least 1 argument (0 given)
>>> "hello".find("e")
1
>>> str.find("hello", "e")
1
在
w+
()模式下打开文件,它将生成一个文件名。并使用file.seek
读取文件
a = "Hello" # no need of brackets
f = open("hello.csv","a")
f.write(a)
f.close()
f = open("hello.csv","r")
f = f.read()
if f.find(a)>0: # find returns position of substring if found else -1
print True
f.close()
来自@Hackaholic这不是一个非常有用的评论…@Hackaholic什么?这是一个问题吗?可能是我不明白。
我正在尝试制作一个程序,将文件写入,然后查找该文件中写入的内容。
@Hackaholic这不是一个代码编写服务;我已经纠正了OP使用的find
,一旦他们了解了如何应用它,就由他们决定如何获得他们想要使用的两个字符串(look_in
和to_find
,在我的回答中)。
a = ("Hello")
with open("hello.csv", 'w+') as f:
f.write(a)
f.seek(0)
print f.read()