[英]How to load a formatted txt file into Python to be searched
我有一个格式不同的缩进格式的文件,它的长度为数百行,我尝试了各种方法将其作为文件和变量加载到python中,但未成功。 什么是加载文件的有效方法。 我的最终目标是加载文件,然后在其中搜索特定的文本行。
with open('''C:\Users\Samuel\Desktop\raw.txt''') as f:
for line in f:
if line == 'media_url':
print line
else:
print "void"
Error: Traceback (most recent call last): File "<pyshell#35>", line 1, in <module> with open('''C:\Users\Samuel\Desktop\raw''') as f: IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\Users\\Samuel\\Desktop\raw
以下是将文件内容读入变量的标准方法:
with open("filename.txt", "r") as f:
contents = f.read()
如果要使用行列表而不是字符串中的整个文件,请使用以下命令:
with open("filename.txt", "r") as f:
contents = list(f.read())
然后,您可以使用搜索文本
if any("search string" in line for line in contents):
print 'line found'
如果您要搜索特定的行,那么最好避免将整个文件加载到以下位置:
with open('filename.txt') as f:
for line in f:
if line == 'search string': # or perhaps: if 'search string' in line:
# do something
如果您尝试在忽略缩进的同时搜索特定行的存在,则需要使用
if line.strip() == 'search string'.strip():
为了在比较之前去除前导(和尾随)空格。
Python使用反斜杠表示“转义”。 对于Windows路径,这意味着将路径指定为“原始字符串”-'r'前缀。
行有换行符。 为了进行比较,将它们剥离。
使用open(r'C:\\ Users \\ Samuel \\ Desktop \\ raw.txt')作为f:对于f中的行:if line.rstrip()=='media_url':打印行else:打印“ void”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.