简体   繁体   English

Python读取文本文件

[英]Python reading text files

Please help I need python to compare text line(s) to words like this.请帮助我需要 python 将文本行与这样的单词进行比较。

with open('textfile', 'r') as f:
    contents = f.readlines()
    print(f_contents)
    if f_contents=="a":
        print("text")

I also would need it to, read a certain line, and compare that line.我也需要它,阅读某一行,并比较该行。 But when I run this program it does not do anything no error messages, nor does it print text.但是当我运行这个程序时,它不会做任何事情,没有错误信息,也不会打印文本。 Also How do you get python to write in just line 1?另外你如何让python只写在第1行? When I try to do it for some reason, it combines both words together can someone help thank you!当我出于某种原因尝试这样做时,它将两个词结合在一起,有人可以帮忙吗谢谢!

what is f_contents it's supposed to be just print(contents) after reading in each line and storing it to contents .什么是f_contents它应该只是print(contents)在读取每一行并将其存储到contents Hope that helps :)希望有帮助:)

An example of reading a file content:读取文件内容的示例:

with open("criticaldocuments.txt", "r") as f:
    for line in f:
       print(line)
       #prints all the lines in this file
       #allows the user to iterate over the file line by line 

OR what you want is something like this using readlines():或者你想要的是这样的使用 readlines():

with open("criticaldocuments.txt", "r") as f:
   contents = f.readlines() 
   #readlines() will store each and every line into var contents 
   if contents == None:
      print("No lines were stored, file execution failed most likely")
   elif contents == "Password is Password":
      print("We cracked it")
   else:
      print(contents)
      # this returns all the lines if no matches

Note:笔记:

contents = f.readlines() 

Can be done like this too:也可以这样做:

for line in f.readlines(): 
#this eliminates the ambiguity of what 'contents' is doing
#and you could work through the rest of the code the same way except 
#replace the contents with 'line'.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM