When my script is run, it asks for an input. That input is then checked to see if it's in a text file. If it is, text is printed. The code I have below is what I have but it doesn't seem to be working, any help would be greatly appreciated!
discordname = input("What's your discord name?: ")
file = open('rtf.txt')
for line in file:
line.strip().split('/n')
if line.startswith(discordname):
file.close()
print("works")
The expression
line.strip().split('\n')
is not mutating the information bound to the name line, which remains unchanged. Instead it returns a new value. You need to bind that new value to a name in order to use use it. This example might help:
In [1]: a = " v "
In [2]: a.strip()
Out[2]: 'v'
In [3]: a
Out[3]: ' v '
In [4]: b = a.strip()
In [5]: a
Out[5]: ' v '
In [6]: b
Out[6]: 'v'
Then split('\n') (note that you probably want \ instead of /) further returns a list of substrings split by newlines. Note that this is not very useful because for line in file: already splits over lines so the list would have one element at most, and so you should omit it.
Here is the Solution:
discordname = input("What's your discord name?: ")
with open('rtf.txt', 'r') as f:
for line in f.readlines():
if line.startswith(discordname):
print ("it works")
I hope it resolve you're problem.thanks
You are probably trying to get strings as input as well. I suggest this:
discordname = raw_input("What's your discord name? ")
with open('rtf.txt') as f:
for line in f:
if discordname in line:
print "works"
You are trying to make the code more complex. Firstly to open a text file use 'with', because it is more flexible and doesn't need closing. Then, instead of using strip, you can use readlines(). This function converts each line into a list or you can also use method read(), which displays all results as it is.
So,
By using readlines, you can look through the user input in a line as a list, and by using read, you can look through each words. Here is the Solution:
discordname = input("What's your discord name? ")
with open('rtf.txt') as file:
contents = file.readlines()
if discordname in contents:
print("It exits")
Works for me, Optimized code is:
result = any(line.startswith(discordname) for line in file.splitlines())
if(result):
file.close()
print "works"
Related
I am a biologist and need to make a quick script to process some files.
The file format is fasta:
>line1
ACCGAGCTACTAGXXXXX
>line2
ACGTAX
et cetera.
I want to remove all X characters and quickly put toghether this script:
print """Input file must be named FILE.fasta"""
fasta_file = raw_input('Input file name:') # Input fasta file
char = raw_input('Which sequence should be stripped?:')
OutFileName = fasta_file.strip('.fasta') + '_stripped.fasta'
OutFile = open(OutFileName, 'w')
WriteOutFile = True
data = open(fasta_file, "r")
for line in data:
if line.startswith('>'):
OutPut = line
else:
OutPut = line.strip(char)
print OutPut
OutFile.write(OutPut)
print(char)
OutFile.close()
quit()
It does not work and I can't figure out why. any help?
P.S. sorry for the terrible code.
The other answers specified better alternatives. But in your case, [Python 3.Docs]: Built-in Types - str.strip([chars]) didn't work because each line in a file ends with the EOLN terminator, so X is not actually at the end of the string.
The option that requires minimum of code changes, is to modify the 3rd line from:
char = raw_input('Which sequence should be stripped?:')
to:
char = raw_input('Which sequence should be stripped?:') + "\n"
Beware: the line fasta_file.strip('.fasta') might not do what you think it does. Here, it would be recommended to use:
fasta_file.replace('.fasta', '_stripped.fasta')
EDIT0:
I think that you need to add the EOLN back when writing to the output file, so you also need to replace this line:
OutPut = line.strip(char)
by:
OutPut = line.strip(char) + "\n"
Use line.replace(char,'') instead line.strip(char)
Strip function removes characters only from sides https://docs.python.org/2/library/string.html#string.strip
You could do this using regex:
import re
pattern = re.compile("(\w[^X]+)") # This groups everything but X
stripped = pattern.match(line).group()
For your case you can do something similar in the 'else' section of your code and replace the 'X' in "(\w[^X]+)" by your 'char' variable:
pattern = re.compile("(\w[^" + char + "]+)")
I have a text file with this in it
Curtain Open time: 8:00
When I wrote to the file I used this
File.write("Curtain Open Time: " + Var_CurtainOpenTime, + "\n")
I used the "\n" to go onto the next line for more data to be wrote. "Var_CurtainOpenTime" is a variable in this case it was "8:00". I have some code to read the line which looks like this:
FileRead = open('File.txt', 'r')
Printing this would read "Curtain Open Time: 8:00".
I want to be able to just get "8:00". I had previously used FileRead.split(" ") to separate each word but after the 8:00 I get ["Curtain", "Open", "Time:", "8:00\n"]. So I believe I would need to remove the first 3 indexes somehow and somehow remove '\n' from the last index. I don't know how I would approach this. Any help?
Try the following, I will comment the explain
with open('File.txt') as f:
[line.replace('\n','').split()[3:][0] for line in f][0]
or just:
FileRead = open('File.txt', 'r')
result = [line.replace('\n','').split()[3:][0] for line in FileRead][0]
you just need to change from the .split(" ") to .split() and then get the last list item
with open('file.txt') as f:
print f.read().split()[-1]
Well once you have the list from the split, you can remove the first 3 terms by doing l=l[3:] (where l is your list). Then you can remove the \n by doing s = s[:-1] where s is your desired string. This is using list slicing. You can look at documentation if you want to understand it further.
I am trying to print a specific line from the file "Scores", which is option B. This is my code:
print("Option A: Show all scores\nOption B: Show a record\nOption Q: Quit")
decision = input("Enter A, B, C or Q: ")
myFile = open("Scores.txt", "rt")
if decision == "A":
record = myFile.read()
print(record)
myFile.close()
elif decision == "B" or decision == "b":
playerName = input("Enter a player name to view their scores: ")
record = myFile.read()
answer = record.find(playerName)
for line in answer:
print(line)
elif decision == "Q" or decision == "q":
exit
I went for Option B, then I entered a player name that holds the score of the player, but it throws this error message:
line 12, in <module>
for line in answer():
TypeError: 'int' object is not callable
A few cents from my side :
file = open("file")
lines = file.readlines()
for line in lines:
if playername in line:
print line
file.close()
Hope it works!
find() method returns a positive index if it succeeds, -1 otherwise
You should loop on your content line by line, as follows:
for line in myFile:
if line.find(playerName):
print(line)
A safer way to read the file and find data, so that you will not have OutOfMemory issues when storing the whole file in memory.
playerName = input("Enter a player name to view their scores: ")
with open("Scores.txt", 'r') as f:
for row in f:
if playerName in row:
print row
This way you will be using with that will close the file by itself either when the program ends or Garbage Collection kicks in. This way python will read the file line by line and store only 1 line in memory. So you can use huge files and do not worry about memory issues.
Hope it helps :)
Working with str methods will take more acrobatics. Try the following,
import re
p = re.compile(r"\b{}\b".format(playername)) # keep it ready
# inside option B
for line in myfile: # no need to `.read()` it
match = p.search(line)
if match:
print(line)
break # if there is only one record for playername
See if it works for you.
similar thing here:
Reading specific lines only (Python)
fp = open("file")
for i, line in enumerate(fp):
if line == playername:
print line
fp.close()
I also notice you don't close your file for each decision, should make that happen.
Few python idioms and small optimization
Here are many answer, my sample brings in few python idioms and optimize it a bit:
fname = "Scores.txt"
player_name = "Quido"
with open(fname) as f:
for line in f:
if player_name in line:
print line
break
print "Going on doing following tasks."
The with block will close the open file on exiting the inner block. No need to f.close(), safe
in case of problems to read the file.
for line in f: shows, that iterating over file open in text mode we get one line per iteration.
break after we print the line with the player will effectively stop iterating over lines assuming,
there is only one such line or that we are happy with the very first one. If this is not the case,
removing the break allows printing all lines containing the player name.
As lines returned from text file iterator contain new line, you may prefer to get rid of them. Use
print line.strip() in such case what will remove all blank characters from start and end of the line.
Final print is proving, the program continues after it processes all the lines.
It may happen, that you get no output for name, which appears to be present in the file. In such a
case, you might need to clarify letter case. For example, if your text file contains all the names
in exact casing, you have to enter the name properly.
Other option is to lower-case the player_name and compare it against lower cased line:
fname = "Scores.txt"
player_name = "Quido"
normalized_player_name = player_name.lower()
with open(fname) as f:
for line in f:
if normalized_player_name in line.lower():
print line.strip()
break # comment out to print all lines with the player
print "Going on doing following tasks."
Note, that we normalize the player_name outside from the loop to be a bit faster. Lower-casing inside the
loop would work, but would do the same task repeatedly.
The line is printed using exact letter cases as in the file.
I have a file in the format of one word for line, and I want to join the lines with one space, I tries this, but it does not work
for line in file:
new = ' '.join(line)
print (new)
also this does not work
new = file.replace('\n'', ' ')
print (new)
You can also use list comprehensions:
whole_string = " ".join([word.strip() for word in file])
print(whole_string)
You can add each line to a list, then join it up after:
L = []
for line in file:
L.append(line.strip('\n'))
print " ".join(L)
Your current solution tries to use join with a string not a list
A one line solution to this problem would be the following:
print(open('thefile.txt').read().replace('\n', ' '))
This is I think what you want..
' '.join(l.strip() for l in file)
yet another way:
with open('yourfilename.txt', 'r') as file:
words = ' '.join(map(str.rstrip, file))
As you can see from several other answers, file is an iterator, so you can iterate over it and at each loop it will give you a line read from the file (including the \n at the end, that is why we're all stripping it off).
Logically speaking, map applies the given function (i.e. str.rstrip) to each line read in and the results are passed on to join.
I need to read a existing file that i wrote using a empty list for users raw_input. Not exactly sure on how I sort the file after reading. After sorting, i need to save it under a different file name and print.
This is what I have so far:
Names=[]
while 1:
Input = raw_input("Enter a name or press 'v' to quit:")
if Input == "v":
break
Names.append(Input)
raw_input ('Press Enter to write each of the names to a file named NAMES.')
text_file= open ("NAMES.txt", "w")
text_file.writelines(Names)
text_file.close()
raw_input('Press Enter to Read file into a sorted list.')
text_file = open("NAMES.txt", "r")
names = text_file.readlines()
text_file.close()
^This is where I need to sort and save under different file name and print. STUCK!
names.sort()
http://wiki.python.org/moin/HowTo/Sorting/
you can just sort the list of names .... names.sort()
>>> names=["John","Angel","Luis"]
>>> names.sort()
>>> names
['Angel', 'John', 'Luis']
Edit: comment answer
writelines doesn't add line separators therefore
when you do text_file.writelines(Names) you are writing just one line.
To write line separators you can do ...
text_file.writelines(map(lambda x: x+'\n',Names))
or simply append \n at the end of each name ...
Names.append(Input+'\n')
This is probably homework, so i'll give you some hints.
You should take a look at the python docs for sorting.
Using the .sort() method for a list will alter the list and give no return value.
>>> a = ['2','1']
>>> a
['2', '1']
>>> a.sort()
>>> a
['1', '2']
Using sorted() on a list, will return the list sorted, and not alter the original list:
>>> a = ['2','1']
>>> sorted(a)
['1', '2']
>>> a
['2', '1']
>>>
As far as reading in the file that you wrote, you probably want to strip the endline characters:
names = [ line.strip() for line in text_file.readlines() ]
Sort the list of names using either of the methods above, and then write to a new file.
Based on this comment:
yes, but when i try to sort it comes
back the same. Here, if I input
a,c,d,b in the raw_input it comes back
as ['acdb']
The reason why you are unable to read the names back correctly is because you are using writelines.
file.writelines(sequence)
Write a sequence of strings to the file. The sequence can be any iterable
object producing strings, typically a
list of strings. There is no return
value. (The name is intended to match
readlines(); writelines() does not add
line separators.)
You could either write the lines to your file as you ask for them:
text_file= open ("NAMES.txt", "w")
while True:
Input = raw_input("Enter a name or press 'v' to quit:")
if Input == "v":
break
text_file.write(Input)
text_file.close()
or you could append an endline character to your inputs:
Names.append(Input+"\n")
Since you aren't using the Names list anyways the first option allows you to forgo creating an unnecessary variable.