This question is possibly a duplicate but any answers i find don't seem to work. I have a .txt file full of this layout:
artist - song, www.link.com
artist2 - song2, www.link2.com
This is my general purpose:
uinput = input("input here: ")
save = open("save.txt", "w+")
ncount = save.count("\n")
for i in range(0, ncount):
t = save.readline()
if uinput in t:
print("Your string " uinput, " was found in" end = "")
print(t)
My intention is: If the userinput word was found in a line then print the entire line or the link.
You want to read the file, but you are opening the file in write mode. You should use r, not w+
The simplest way to iterate over a file is to have a for loop iterating directly over the file object
Not an error but a nitpick. You do not close your file. You can remedy this with with.. as context manager
uinput = input("input here: ")
with open("save.txt", "r") as f:
for line in f:
if uinput in line:
print('Match found')
You can use list-comprehension to read the file and get only the lines that contain the word, for example:
with open('save.txt', 'r') as f:
uinput = input("input here: ")
found = [line.rstrip() for line in f if uinput.lower() in line.lower()]
if found:
print('Found in these lines: ')
print('\n'.join(found))
else:
print('Not found.')
If you want to print the link only, you can use:
found = [line.rstrip().split(',')[1] for line in f if uinput.lower() in line.lower()]
You can use list comprehension to fetch the lines containing user input words.
use below code:
try:
f = open("file/toyourpath/filename.txt", "r")
data_input = raw_input("Enter your listed song from file :");
print data_input
fetch_line = [line for line in f if data_input in line]
print fetch_line
f.close()
except ValueError, e:
print e
Related
I have a file which contains my passwords like this:
Service: x
Username: y
Password: z
I want to write a method which deletes one of these password sections. The idea is, that I can search for a service and the section it gets deleted. So far the code works (I can tell because if you insert print(section) where I wrote delete section it works just fine), I just don't know how to delete something from the file.
fileee = '/home/manos/Documents/python_testing/resources_py/pw.txt'
def delete_password():
file = open(fileee).read().splitlines()
search = input("\nEnter Service you want to delete: ")
if search == "":
print("\nSearch can't be blank!")
delete_password()
elif search == "cancel":
startup()
else:
pass
found = False
for index, line in enumerate(file):
if 'Service: ' in line and search in line:
password_section = file[index-1:index+3]
# delete password_section
found = True
if not found:
print("\nPassword for " + search + " was not found.")
delete_password()
Deleting a line from the file is the same as re-writing the file minus that matching line.
#read entire file
with open("myfile.txt", "r") as f:
lines = f.readlines()
#delete 21st line
del lines[20]
#write back the file without the line you want to remove
with open("myfile.txt", "w") as f:
f.writelines(lines)
I have a multiline string, which needs to be pasted and saved into a .txt file. I need also use some characters from the string as file name.
Here is an input example:
ABCD 0000/20/02
Q) abc/yxz/IV/A /000/999
A) XYZ B) 2008311600 C) 2009301559
E) texttexttext
texttext
File name should contain 6 numbers after B) : 200831 and the extension txt.
That's what I have:
print ('Paste new NOTAM starting with AXXXX/20: ') ##paste notam
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
file_name= line[line.find("B) ")[6]:]
print (file_name)
with open(input(file_name + '.txt', "w+")) as f:
for line in lines:
f.write(line)
f.write('\n')
You could use regex to find out file name:
import re
string = '''ABCD 0000/20/02<br />
Q) abc/yxz/IV/A /000/999<br />
A) XYZ B) 2008311600 C) 2009301559<br />
E) texttexttext<br />
texttext<br />'''
filename = re.findall('B\) (\d\d\d\d\d\d\d)', string)[0]
with open(f'{filename}.txt', 'w') as f:
f.write(string)
Output file is 2008311.txt
so here i'm pasting my input, which is multiline string:
print ('Paste new NOTAM starting with AXXXX/20: ') ##paste notam
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
Now i need to simply use those 6 characters from already pasted input in file name
In your code, all lines need to be checked, not only one line, so:
for line in lines:
if "B)" in line:
file_name = line[line.find("B) ")[6]:]
print (file_name)
Then, it is not really clear from your question whether you keep all multiline strings in memory or in separate files. Either way, you can write a function so that you can use it in different scenarios:
def parse_lines(lines):
for line in lines:
if "B)" in line:
file_name = line[line.find("B) ")[6]:]
print (file_name)
with open(file_name + '.txt', "w+") as f:
for line in lines:
f.write(line)
f.write('\n')
So your code will look like this:
print ('Paste new NOTAM starting with AXXXX/20: ') ##paste notam
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
parse_lines(lines):
Or if you plan to parse batch files with this method:
import sys
with open(sys.argv[0], 'r') as f:
lines = f.readlines()
parse_lines(lines)
I am going through Intro to Programming so basic stuff here, I have an assignment to "write a program that asks a user for a file name and then displays the first 5 lines of the file," I just can't figure out how to use the input command in this situation and then transfer to open()
Edit: Sorry here is a code snippet I had, I just don't get how to apply input from here.
def main():
#This function writes to the testFile.docx file
outfile = open('testFile.docx', 'w')
outfile.write('Hello World\n')
outfile.write('It is raining outside\n')
outfile.write('Ashley is sick\n')
outfile.write('My dogs name is Bailey\n')
outfile.write('My cats name is Remi\n')
outfile.write('Spam Eggs and Spam\n')
outfile.close()
infile = open('testFile.docx', 'r')
testFileContent = infile.read()
infile.close()
print(testFileContent)
main()
First, we ask for a filename. Then we use the try clause, which checks whether the file exists. If it does it will print 5 lines. If it does not, it will print No such a file found!
x = input('Enter a file name')
try:
with open(x) as f:
data = f.readlines()
for i in range(5):
print(data[i])
except:
print('No such a file found!')
Using a simple function,
def hello_user():
user_input = input('Enter file name: ')
try:
with open(user_input, 'r') as f:
data = f.readlines()
data = data[:5]
for o in data:
print(o.strip())
except FileNotFoundError:
print('Not found ')
hello_user()
It asks for a file name
If the file exists in the same directory the script is running, it opens the file and read each lines (white lines inclusive)
We select only the first 5 lines
We iterate through the list and remove the extra whitespace character(e.g \n).
If the file was not found, we catch the exception.
input() is used to receive input from the user. Once we recieve the input, we use the open() method to read the file in read mode.
def main():
file = input("Please enter a file name")
with open(file, 'r') as f:
lines = f.readlines()
print(lines[:5])
The with statement makes sure that it closes the file automatically without explicitly calling f.close()
The method f.readlines() returns an array containing the lines in the file.
The print() statement prints the first 5 lines of the file.
Writing a program to check if a word that the user inputs is in a pre-existing set; no matter what word I input the program returns "False" (even when it's a word I know is in the set). Code is below:
name = input("which file would you like to open? ")
s=input("word? ")
F = open(name, "r")
words = set()
words.add(F)
def contains(s,words):
if s in words:
print("true")
else:
print("false")
contains(s,words)
Assuming there is one word per line in the file, e.g.
asd
asdf
You can use this, which adds every line to words:
name = input("which file would you like to open? ")
s = input("word? ")
F = open(name, "r")
words = set()
for line in F: # add every line to words (assuming one word per line)
words.add(line.strip())
def contains(s, words):
if s in words:
print("true")
else:
print("false")
contains(s, words)
Printing an output of:
which file would you like to open? file.txt
word? asd
true
Edit: a much shorter way for the actual task:
name = input("which file would you like to open? ")
s = input("word? ")
F = open(name, "r")
print("true") if s in F.read() else print("false")
Assuming your file looks like this:
banana
apple
apple
orange
Let's create that file:
with open("test.txt","w") as f:
f.write("banana\napple\napple\norange")
Now let's run a sample code:
s= input("word? ")
words = set()
# Using with we don't need to close the file
with open("test.txt") as f:
# here is the difference from your code
for item in f.read().split("\n"):
words.add(item)
def contains(s,words):
for word in words:
if s in word:
print("true")
break
else:
print("false")
contains(s,words)
Typing:
apple returns "true"
ap returns "true"
oeoe returns "false"
The right way is to use a generator for this:
name = input("which file would you like to open? ")
word_to_look_for=input("word? ")
def check(word_to_look_for, word_from_file):
return word_to_look_for == word_from_file
with open(name, "r") as file:
# The code inside the parentheses () returns a generator object
word_exists = (check(word_to_look_for, word_from_file.rstrip("\n")) for word_from_file in file.readlines())
# This will return true if either one of the "check" function results is True
print(any(word_exists))
For first, it's better to open files using
with open(filepath, 'r') as input_file:
you could read about this here
https://docs.python.org/3/tutorial/inputoutput.html
Also you try to add file into set, but you need to add words.
So this is working (and more pythonic) code:
import os
def load_data(filepath):
if not os.path.exists(filepath):
return None
with open(filepath, 'r') as input_file:
text = input_file.read()
return text
if __name__ == '__main__':
filepath = input("Which file would you like to open?")
word=input("What we want to find?")
text = load_data(filepath)
if not text:
print("File is empty or not exists!")
raise SystemExit
words = set(text.split())
print(word in words)
There are a few things going on here which I'm not sure you're totally clear on:
First, F is a file. I'm going to guess that you're intention here is that you're trying to check whether a word is in a file of words (like a dictionary). To do this however you'll need to do something like this:
filename = "somefilename.txt"
words = set()
# open the file
file = open(filename, "r")
# read the lines into an array
lines = file.readlines()
for line in lines:
words.add(line)
testWord = input("word? ")
The second issue is that you're using a function but you're mistaking your parameters as the same variables you've declared in your main flow. Eg.
# this is a verbose way of doing this
words = set()
testWord = input()
def isWordInSet(word, words):
# words here is not the same as the words
# outside the function
if word in words:
print("True")
else:
print("False")
isWordInSet(testWord, words)
I am wanting to print the results shown in my console from the loop below into a text file. I have tried putting this code in the loop as seen in the example:
f = open('out.txt', 'w',)
sys.stdout = f
However when this is in the loop I only get one set of results instead of the full expected.
wordlist = input("What is your word list called?")
f = open(wordlist)
l = set(w.strip().lower() for w in f)
chatlog = input("What is your chat log called?")
with open(chatlog) as f:
found = False
for line in f:
line = line.lower()
if any(w in line for w in l):
print (l)
print(line)
found = True
f = open('out.txt', 'w',)
sys.stdout = f
if not found:
print("not here")
You should use write() function to write your result into the file.
Code should be something as:
wordlist = input("What is your word list called?")
f = open(wordlist)
l = set(w.strip().lower() for w in f)
chatlog = input("What is your chat log called?")
with open(chatlog) as f:
found = False
file = open("out.txt", "w")
for line in f:
line = line.lower()
if any(w in line for w in l):
found = True
file.write(line)
if not found:
print("not here")
You should make sure that you open the 'out.txt' for writing outside the loop, not inside the loop
If you want to write text to a file, you should use the .write() method of the File object, as specified in https://docs.python.org/2/tutorial/inputoutput.html, rather than the print method.
The problem is, each iteration you open it with write mode
Due to python documentation:
'w' for writing (truncating the file if it already exists)
for your purposes you should use "a" mode (append) or open file out of cycle