I didnt know how to word the title, but here's the code:
file = open('blah.txt', 'r')
line = file.read()
file.close()
stuff = input('enter stuff here')
if stuff in line:
print('its in the file')
else:
print('its not in the file')
and here's blah.txt:
text,textagain,textbleh
If the user input is found in the file, is there a way to also output the position of the string entered by the user? For example, if the user entered 'textagain', is there a way to output '2' because the string 'textagain' is in the second position in the file?
Thank you in advance.
What #Amiga500 said would likely work with some wrangling, I suggest splitting your strings up.
"text,textagain,textbleh".split(",") would return ['text', 'textagain', 'textbleh'] at which point you can do .index(your_word) and get back the index (1 for textagain since Python uses zero based indexing and it is the second entry).
So the final code might be:
file = open('blah.txt', 'r')
line = file.read()
file.close()
stuff = input('enter stuff here')
if stuff in line.split(","):
print('its in the file')
else:
print('its not in the file')
Try this:
line.index(stuff)
i.e.
if stuff in line:
posit = line.index(stuff)
If you try jumping straight to the index and its not there, it'll throw an error. You could use a try except as a workaround, but its ugly.
Ah, sorry, misread. You've a csv file.
Use the csv reader in python to read it in:
Python import csv to list
Then loop through (assuming line is the sub-list for each line):
if stuff in line:
posit = line.index(stuff)
Related
I have a text file with some data in it, and i've written a code that is supposed to delete a specific line when te if statement is true. Why does python delete every line except the first one? And how do i fix it?
def give_back():
number_input = input('What is ur number?')
code_input = input('Enter the code corresponding to your number.')
b = [f'{number_input};{code_input}']
with open('fa_kluizen.txt', 'r') as f:
x = f.readlines()
with open('fa_kluizen.txt', 'w') as f:
for line in x:
if line.strip('\n').strip() != b:
f.write(line)
return True
else:
return False
You have two basic issues. The first is the way you handle your loop:
def give_back():
...
return True # leaves the function `give_back`
Even though you have a for line in x between these two statements, it will only ever run the first loop because you use the keyword return. This leaves the function. If you expect more work to be done, you need to avoid doing this.
Secondly, you are using the read-write flags awkwardly. When you open a file with open('somefile.txt', 'w') it opens for writing, truncating (deleting the contents of) the file first. If you plan to write every line back, that is fine, but since your loop only occurs once, the first line will be all that is in the file when you're done.
You don't say what you want the actual end result to look like with a given input, so it's impossible to say what the correct way to fix this is, but I'd start by getting rid of your return statements and see whether that matches what you're looking for.
You probably meant something like this:
def give_back():
number_input = input('What is ur number?')
code_input = input('Enter the code corresponding to your number.')
b = [f'{number_input};{code_input}']
with open('fa_kluizen.txt', 'r') as f:
x = f.readlines()
with open('fa_kluizen.txt', 'w') as f:
for line in x:
if line.strip('\n').strip() != b:
f.write(line)
The problem is that if u return the function exits
I currently have a working phonebook with 4 options. The only thing is, the search option is not printing all of the matches.
If I type a name and there is a match in the phonebook it will print that line into a text file (phone.txt02, which is blank).
Then after all of the matches have been printed to the text file, my program reads the new text file and returns them in my preferred format.
The readFile function isn't working properly right now for the new text file.
It works fine on phone.txt (the original text file) which contains the same information... Names and numbers separated by a comma.
Because this works, I cannot figure out why the readFile function will not work for phone02.txt when the values are also name,number \n
def readFile1(filename):
phonebook = []
file = open(filename, "r")
for aline in file:
person = aline.split(",")
if person[1][-1] == '\n' :
pn = person.pop(1)
person.append(pn[:-1])
phonebook.append(person)
elif person[1][-1] != '\n' :
phonebook.append(person)
file.close()
return phonebook
def printEntries1(phonebook):
readFile1("phone02.txt")
print("Name Phone Number")
print("------------------- --------------")
for i in range (len(phonebook)):
person = phonebook[i]
print(i,"{:<20s} {:>14s}".format(person[0],person[1]))
print("------------------- --------------")
def searchEntry():
search = input("Type a name to search for")
with open("phone.txt", "r") as file:
lines = file.readlines()
for line in lines:
if search in line:
outfile = open("phone02.txt", "a")
outfile.write(line)
phonebook = readFile1("phone02.txt")
print(readFile1("phone02.txt"))
printEntries1(phonebook)
outfile = open("phone02.txt", "r+")
outfile.truncate()
print(searchEntry())
I am not sure how to have the printEntries print all of the matches (name and number) from phone02.txt
Here is an example of the phone.txt file
Polly,549-5393
Bud Wieser,(213) 477-3928
Jack,277-4829
Mike Dunleavy,335-3453
Robert Darn,219-473-4373
Earl Lee,703-304-8393
Tim Bean,(612) 493-2629
Bud,(701) 487-8522
If I were to input "Bud" it would print the 2 lines that contain bud to phone02.txt but not print them correctly.
It seems that (in this example) when the 2 lines containing Bud are put into phone02.txt, only the first line is printing
Name. Number
------------------- ------------------
0 Bud Wieser. (218) 477-3928
I know this is a lot of information for most likely an easy fix, but I think it should help with the issue.
Thanks for any help.
You never closed the writer to phone02.txt. All new lines will be saved in the file only after you close the file writer or directly tell python to do save the changes to the file. Please try
if search in line:
outfile = open("phone02.txt", "a")
outfile.write(line)
outfile.close()
Anyway, you open the file for reading many times -- please either do it once before the loop and close afterwards, or open and close the writer for each iteration.
I have a text file that contains
### 174.10.150.10 on 2018-06-20 12:19:47.533613 ###
IP : 174.10.150.10 :
IP : ALL :
I currently have code that uses Regex to search for a date/time string.
How can I delete a line that contains the string that I find? I want to delete that line and also the line underneath.
So both of these lines would get deleted:
### 174.10.150.10 on 2018-06-20 12:19:47.533613 ###
IP : 174.10.150.10 :
My code currently just adds 'None' to the bottom of the text file.
import re
def run():
try:
with open('file.txt', 'r') as f:
with open('file.txt', 'a') as f2:
reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###')
for line in f:
m = reg.match(line)
answer = raw_input("Delete line? ")
if answer == "y":
# delete line that contains "###" and line underneath
f2.write(str(m))
else:
print("You chose no.")
except OSError as e:
print (e)
run()
(EDIT: I now understand from your comments that you have a blank line after two data lines, so when you want to delete a line you also want to delete the next two lines. My code has been adjusted to do that.)
Here is some code, making various changes to your code. I wrote a new file rather than overwriting the old file, for safety and to avoid needing to keep the entire file in memory at once. I combined the with lines into one line, for readability; similarly, I split the regex string to allow shorter lines of code. To avoid having more than one line in memory at once, I used a countdown variable skipline to note if a line is to be skipped in the new file. I also show each line before asking whether or not to delete it (with its following line). Note that lines that do not have the date and time are copied, by checking that the regexp match variable is None. Finally, I changed raw_input to input so this code will run in Python 3. Change it back to raw_input for Python 2.
By the way, the reason your code just adds 'None' to the end of the file is that you put your write line outside the main loop over the lines of the file. Thus you write only the regex match object for the last line of the file. Since the last line in your file does not have a date and time, the regex did not match so the string representation of the failed match is 'None'. In your second with statement you opened file.txt in append mode, so that 'None' is appended to the file.
I want to emphasize that you should create a new file. If you really want to overwrite the old file, the safe way to do that is to create a new file first with a slightly different name. Then if that file is made successfully, overwrite the old file with the new file and rename one copy to something like file.bak. This takes possible OS errors into account, as your code attempts to do. Without something like that, an error could end up deleting your file completely or mangling it. I leave that part of the code to you.
import re
def run():
try:
with open('file.txt', 'r') as f, open('file.tmp', 'w') as f2:
reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
'.+(\d{4}-\d{2}-\d{2}\s\d{2}'
':\d{2}:\d{2}.\d{0,})\s###')
skipline = 0 # do not skip lines
for line in f:
if skipline:
skipline -= 1
continue # Don't write or process this line
m = reg.match(line)
if m:
answer = input("Delete line {} ? ".format(m.group()))
if answer == "y":
skipline = 2 # leave out this and next 2 lines
else:
print("You chose no.")
if not skipline:
f2.write(line)
except OSError as e:
print(e)
run()
I refactor the filtering part into a function called filter_lines and move the regex as module variable. This approach make use of iterator.
import re
regex = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###')
def filter_lines(lines):
it = iter(lines)
try:
while True:
line = next(it)
m = regex.match(line)
if m:
# You may add the question-answer code here to ask the user whether delete the matched line.
next(it) # Comsume the line following the commented line
continue
yield line
except StopIteration:
# In the future, StopIteration raised in generator function will be converted to RuntimeError so it have to be caught.
# https://www.python.org/dev/peps/pep-0479/
pass
def run():
try:
with open('file.txt', 'r') as f:
with open('file.txt', 'a') as f2:
filtered_lines = list(filter_lines(f1.readlines()))
print(*filtered_lines, sep='')
# You may use the following line to actually write the result to a file
# f2.writelines(filtered_lines)
except OSError as e:
print (e)
run()
This program should print the resultant content.
With some basic refactoring, here's the result...
import re
valid_lines = []
def run():
try:
with open('file.txt', 'r') as f:
reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###\s?')
lines = f.readlines()
invalid_index = -10
for a in range(len(lines)):
reg_result = reg.match(lines[a])
if invalid_index == (a - 1):
# Skip the line underneath the invalid line
continue
if reg_result != None:
# If the line matches the regexp.
invalid_index = a
answer = raw_input("Delete line? ")
if answer.lower() != 'y':
print("You chose no.")
valid_lines.append(lines[a])
else:
valid_lines.append(lines[a])
with open('file.txt', 'w') as f:
# Override the file...
f.writelines(valid_lines)
except OSError as e:
print (e)
run()
If you want to remove any lines that start with ### then, maybe you should consider this as the regexp: ###.*
EDIT: In your regular expression, you should add a \s? at the end to optionally match \n, as the file contains newlines. Also, use fullmatch() instead of match().
I have a txt file with strings assigned to each other like "sun - moon" and I want to get the assigned value (no matter which one) of a particular string if it would come from user input, and if not then create a new pair for file and write it to it:
user_input = input()
if user_input in open('base.txt').read():
print(True) # it's just to be sure that everything really works
else:
base_file = open('base.txt', 'a+')
base_file.write(user_input)
base_file.write('\n')
base_file.close()
import pickle
myDictA = {'sun': 'moon'}
with open('myFile.pkl', 'w') as file:
pickle.dump(myDict, file)
with open('myFile.pkl', 'r') as file:
myDictB = pickle.load(file)
print("myDictA:", myDictA)
print("myDictB:", myDictB)
you can also integrate gzip in the file save load process to save disk space if you want. Another option is to use cPickle which should be written the same way and is said to be up to 1000x faster.
A little addition to the current code.
user_input = input()
flag=1
with open('base.txt') as f:
data=f.read()
if user_input in data:
print(data)
flag=0
if flag:
base_file = open('base.txt', 'a+')
base_file.write(user_input)
base_file.write('\n')
base_file.close()
I'm really desperate for some help on this python code please. I need to search for a variable (string), return it and the data present on the same line as the variable data.
I've managed to create a variable and then search for the variable in a text file, however if the data contained in the variable is found in the text file the contents of the whole text file is printed out not the line in which the variable data exists.
This is my code so far, please help:
number = input("Please enter the number of the item that you want to find:")
f = open("file.txt", "r")
lines = f.read()
if lines.find("number"):
print (lines)
else:
f.close
Thank you in advance.
See my changes below:
number = input("Please enter the number of the item that you want to find:")
f = open("file.txt", "r")
lines = f.read()
for line in lines: # check each line instead
if number in line: # if the number you're looking for is present
print(line) # print it
It goes like
lines_containg_number = [line for line in lines if number in line]
What this'll do is give you all the lines in the text file in the form of a list and then you can simply print out the contents of the list...
If you use 'with' loop, you don't have to close file. It will be handled by with. Otherwise you have to use f.close(). Solution:
number = input("Please enter the number of the item that you want to find:")
with open('file.txt', 'r') as f:
for line in f:
if number in line:
print line