okay. you didnt understand anything from the title. let me explain.
now ı have a file. There is some text in this file. for example "jack.123 jackie.321"
I want to check if the word jack exists in the file and ı wanna print "jack.123".
its my problem. ı didnt print all text.
def append(name,password):
f = open("myfile.txt", "w")
f.write("{},{}".format(name,password))
append("jack",".123")
append("jackie" , ".321")
f = open("myfile.txt" ,"r")
if "jack" in f.read():
print("query found")
Open the file and read all its contents then split on whitespace. That effectively gives you all the words in the file.
Iterate over the list of words checking to see if a word starts with the name you're searching for followed by '.'.
Note that there may be more than one occurrence so build a list.
def find_name(filename, name):
if not name[-1] == '.':
name += '.'
found = []
with open(filename) as myfile:
for word in myfile.read().split():
if word.startswith(name):
found.append(word)
return found
print(*find_name('myfile.txt', 'jack'))
def new_pass(name, passwd):
"creates file and write name and passwd to it"
with open("myfile1.txt", "a") as f:
f.write(name + "." + passwd + "\n")
new_pass("jack", "123")
new_pass("jack", "183")
new_pass("jack", "129")
new_pass("jack", "223")
def check_word(file, word):
"""checks if a word exists and returns its first occurence """
with open(file) as f:
l = f.read().split("\n")
for i in l:
if i.startswith(word):
print("query found")
return i
print(check_word("myfile1.txt", "jack"))
In python you can do it like that :
with open('file.txt', 'r') as file:
data = file.read()
if "jack" in data:
print("jack")
If I understood uncorrectly let me know
Related
I need help reading through a text file to search for a user input word, then copying data from that text file to another text file without the user input word.
def remove(infile, outfile, target):
for line in infile:
for word in line.split():
if word != target:
outfile.write(word)
def main():
outfile = open('outputFile.txt', 'w')
infile = open('inputFile.txt', 'r')
#Ask user for word they would like to omit from outfile
target = input("What word would you like to delete from input file?: ")
remove(infile, outfile, target)
infile.close()
outfile.close()
main()
The code above works correctly. It searches the first text file for the user input word and writes to a new file, but it doesn't write out with the proper spacing. It is all on one line and doesn't have any spaces. How do I write to the new file with the same spaces, and \n as the original document?
def remove(infile, outfile, target):
for line in infile:
for word in line.split(' '):
if word != target:
outfile.write(word+' ') # You forgot to add the space that was removed while splitting the line.
outfile.write('\n') # you also forgot to add the newline
def main():
outfile = open('outputFile.txt', 'w')
infile = open('inputFile.txt', 'r')
#Ask user for word they would like to omit from outfile
target = input("What word would you like to delete from input file?: ")
remove(infile, outfile, target)
infile.close()
outfile.close()
main()
I want to basically remove all the characters in delete list from the file (Line 11 to 15). What would be the neatest way to delete the words without making the code not neat. I am not sure whether to open the file again here which I know would not be the right way but I can't think of a different solution. Any help would be appreciated.
from os import write
import re
def readText():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt') as f:
print(f.read())
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
#I want to basically remove all the char in delete list from the file. What would be the neatest way to delete the words without making the code not neat. I am not sure wether to open the file again here and re write it or what!
deleteList = ['!','£','$','%','^','&','*','()','_','+']
for line in f:
for word in deleteList:
line = line.replace(word, '')
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + long)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
f.write(users_text)
f.close()
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as file:
print(file.read())
longestWord()
Had to re work it and implement it in a different def. Need to add relative paths and will be alot cleaner aswell.
from os import write
import re
def longestWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r+') as f:
users_text = f.read()
longest = max(users_text.split(), key=len)
count_longest = str(len(longest))
print('The longest word in the file is: ' + longest)
print('Thats a total of '+count_longest+' letters!')
def writeWord():
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'w') as f:
users_text = input('Enter your desired text to continue. \n: ')
cleanText = re.sub('[^a-zA-Z0-9 \n\.]', ' ', users_text)
f.write(cleanText)
with open(r'C:\Users\maxth\Desktop\TextCounter\Text.txt', 'r') as clean:
print('\nRemoved any illegal characters. Here is your text:\n\n' + cleanText + '\n')
f.close()
while True:
print("""
Welcome to Skies word text counter!
====================================================
""")
writeWord()
longestWord()
userDecide = input("""
====================================================
Would you like to enter new text and repeat?
Type 'yes' to continue else program will terminate.
====================================================
: """)
if not userDecide.lower == 'yes':
print('Application closing...')
exit()
I am attempting to loop through a series of text files in a directory, looking for occurences of certain types of words, and prefixing each found word with a user defined tag. My code is as follows.
ACC_Tagged_Test = 'C:/ACC_Tag_Test'
for filename in glob.glob(os.path.join(ACC_Tagged_Test, '*.txt')):
with open(filename) as f:
data = f.read()
data = data.lower()
modals = {"could":1, "would":1, "should":1, "can":1, "may":1, "might":1}
personal_attribute = {"believes":1, "guess":1, "surmise":1, "considers":1,
"presume":1, "speculate":1, "postulate":1, "surmised":1, "assume":1}
approx_adapt = {"broadly":1, "mainly":1, "mostly":1, "loosely":1,
"generally":1, "usually":1,"typically":1, "regularly":1, "widely":1}
plaus_shields = {"wonder":1, "suspect":1, "theorize":1, "hypothesize":1,
"cogitate":1, "contemplate":1, "deliberate":1}
format_modal = "<555>{} ".format
format_attribute = "<666>{} ".format
format_app_adaptor = "<777>{} ".format
format_plaus_shield = "<888>{} ".format
data = " ".join(format_modal(word) if word in modals else word for word in data.split())
data = " ".join(format_attribute(word) if word in personal_attribute else word for word in data.split())
data = " ".join(format_app_adaptor(word) if word in approx_adapt else word for word in data.split())
data = " ".join(format_plaus_shield(word) if word in plaus_shields else word for word in data.split())
with open (filename, "w") as f:
f.write(str(data))
print(data) # This is just added in order to check on screen all files
# Are being processed.
My problem is that although code works on the last file in the directory it is not working on the previous files (1 out of 10 in this) I've tried a second For loop above the file write out statements but that is not working at all. Can anyone explain what I'm doing wrong here?
regards
My speculation is your code is only showing the last file because it's
not indented properly to have all relevant code within the for loop.
Try with this indentation:
ACC_Tagged_Test = 'C:/ACC_Tag_Test'
for filename in glob.glob(os.path.join(ACC_Tagged_Test, '*.txt')):
with open(filename) as f:
data = f.read()
data = data.lower()
modals = {"could":1, "would":1, "should":1, "can":1, "may":1, "might":1}
personal_attribute = {"believes":1, "guess":1, "surmise":1, "considers":1,
"presume":1, "speculate":1, "postulate":1, "surmised":1, "assume":1}
approx_adapt = {"broadly":1, "mainly":1, "mostly":1, "loosely":1,
"generally":1, "usually":1,"typically":1, "regularly":1, "widely":1}
plaus_shields = {"wonder":1, "suspect":1, "theorize":1, "hypothesize":1,
"cogitate":1, "contemplate":1, "deliberate":1}
format_modal = "<555>{} ".format
format_attribute = "<666>{} ".format
format_app_adaptor = "<777>{} ".format
format_plaus_shield = "<888>{} ".format
data = " ".join(format_modal(word) if word in modals else word for word in data.split())
data = " ".join(format_attribute(word) if word in personal_attribute else word for word in data.split())
data = " ".join(format_app_adaptor(word) if word in approx_adapt else word for word in data.split())
data = " ".join(format_plaus_shield(word) if word in plaus_shields else word for word in data.split())
with open (filename, "w") as f:
f.write(str(data))
print(data) # This is just added in order to check on screen all files
# Are being processed.
Assuming all of your code is supposed to be in your for loop. You are overriding your text file, therefore it looks like only your last run is working:
#this overrides the file
with open(filename, "w") as fh:
fh.write(str(data))
change to:
#this append to the file
with open(filename, "a") as fh:
fh.write(str(data))
This will append to your text file and will not override previous added data with the data from the last loop.
I have a file xyz.txt which has some values assigned to different variables like below.
abc.def = "Hi how are you"
abc.def.ghi = "Hi I am fine"
abc.def.ghi.jkl = "What are you doing"
abc.def.ghi.Mno = "I am working"
I want to write a python generic function which reads the line abc.def.ghi.Mno and changes the string from "I am working" to "I am playing"
This function should also be used for other files also.
I tried with line.startswith(abc.def.ghi.Mno) but its not working.
Below is what I tried.
Thanks in advance.
def find_replace(new_value, start_str, filename):
result = ""
with open(filename) as f:
for line in f:
if line.lower().startswith( start_str ):
list = line.split('=')
list[1] = new_value + '\n'
line = "=".join( list )
result += line
f = open(filename, 'wt')
f.write(result)
f.close()
find_replace(new_value = "I am playing", start_str = "abc.def.ghi.Mno", filename=xyz.txt)
You almost got it. You simply unnecessarily made line lowercase before testing if it starts with "abc.def.ghi.Mno", a mixed-case string, so it naturally wouldn't be true. Remove .lower() and it should work.
There are a number of issues with your code. As blhsing mentioned, one is that line.startswith() is case sensitive, so calling .lower() will not match your start_str. You'll also want to make sure the filename is a string (add quotes). If you want to add the quotes back in as in your original xyz.txt, just escape them when you add the string add them to your list:
def find_replace(new_value, start_str, filename):
result = ""
with open(filename) as f:
for line in f:
if line.lower().startswith( start_str ):
list = line.split('=')
list[1] = "\"" + new_value + "\"\n"
line = "=".join( list )
result += line
f = open(filename, 'wt')
f.write(result)
f.close()
find_replace(new_value = "I am playing", start_str = "abc.def.ghi.Mno", filename="xyz.txt")
I have tried to create a python function which takes in 2 parameters; a file name and a search string. In this case the file name is the script itself (script.py) and the search string is 'name = "JOHN"'
#!/usr/local/bin/python2.7
import os, sys
#################
# Variable string
name = "JOHN"
#################
# Main function
def search_script_for_string(filename, searchString):
f = open(filename,'r') #open the given filename then
filedata = f.read() #assign it to variable then
f.close() #close the open filename
for lines in filedata: #loop through each line in the filedata variable
if searchString in lines: #if search string is found, then do all of this
print ('Found string: %s') % searchString
return True
else: #if not found, then do all of this
print ('Did not find: %s') % searchString
return False
break
#################
# Pass the file name and the search string parameter to the function
search_script_for_string("test.py","name = \"" + name + "\"")
The problem is that it doesn't return expected results:
$ Did not find: name = "JOHN"
When it meant to say:
$ Found string: name = "JOHN"
If anyone can help correct my understanding of where I'm going wrong here, I'd be massively appreciative. Thanks
f.read() returns the entire contents of the file as a single string. You then iterate over those contents -- but iterating over a string yields only 1 character at a time so there is no way a character will contain the substring you are looking for.
def search_script_for_string(filename, searchString):
with open(filename, 'r') as f:
return searchString in f.read()
should do the trick. Alternatively, if you want to search line-by-line:
def search_script_for_string(filename, searchString):
with open(filename, 'r') as f:
for line in f:
return searchString in line
You are iterating over each character of the file by calling for c in f.read().
Use for line in f and you will indeed iterate over each line.
Also prefer the use of with, this makes your code a lot more robust.
So this would be better:
with open('fileName') as f:
for line in f:
#process