write in capital letters? - python

i have the next code:
bestand = open("6_frame.txt", "r")
seq = bestand.readlines()
#to make a list
for line in seq:
alle = line
while True:
if alle.isupper():
break
else:
print ("try again ")
with this code i want to make sure that someone , who write a sequence in the file, write this sequence in capital letters, and want to except the other errors: but he want do what i want.
can somebody help me ??

I think you are saying you want to ensure the entire file is in upper-case. If that's what you are looking for, this will do the trick:
if all(x.isupper() for x in open("6_frame.txt", "r")):
print("entire file is upper-case.")
else:
print("try again!")
This will test the file, line-at-a-time, for all upper-case characters. If it finds a line that is not, it will return false, otherwise if all lines are upper-case, return true (and print "entire file is upper-case").
Update (File watching edition)
It looks like you want to keep checking the file until it's all uppercase. Here's a fairly ineffecient way to do it (you could add modtime checks, or use inotify to make it better):
from time import sleep
while True:
lines = open("6_frame.txt", "r")
if all((x.isupper() or x.isspace()) for x in lines):
print("entire file is upper-case.")
break # We're done watching file, exit loop
else:
print("try again!")
sleep(1) # Wait for user to correct file
Also, you may get exceptions (I'm not sure) if the person is mid-save when your script checks the file again, so you may need to add some exception catching around the all line. Either way... Hope this helps!

My abc.txt content is aBC, so not all uppercase:
fd = open('abc.txt','r')
seq = fd.readlines()
for line in seq:
if line.isupper():
print('all capital')
else:
print('try again')
therefore my output = try again
if my abc.txt content is ABC my output is all capital

Determine whether all cased characters in the file are uppercase, retry if not:
import time
from hashlib import md5
hprev = None
while True:
with open("6_frame.txt") as f:
text = f.read()
if text.isupper():
print('all capital')
break
else:
h = md5(text).hexdigest()
if h != hprev: # print message if the file changed
print('try again')
hprev = h
time.sleep(1) # wait for the file to change

Related

How to search and print a line from txt file in python3?

So I'm learning python3 at the moment through university - entirely new to it (not really a strong point of mine haha), and i'm not quite sure what i'm missing - even after going through my course content
So the program in question is a text based Stock Management program
and part of the brief is that i be able to search for a line in the text file and print the line on the program
def lookupstock():
StockFile = open('file.txt', 'r')
flag = 0
index = 0
search = str(input("Please enter in the Item: "))
for line in StockFile:
index += 1
if search in line:
flag = 1
break
if flag == 0:
print(search, "Not Found")
else:
print(search)
StockFile.close()
However the output is only what i have typed in if it exists rather than the whole line itself so lets say the line i want to print is 'Kit-Kat, 2003, 24.95' and i search for Kit-Kat
Since the line exists - the output is only
Kit-Kat
Rather than the whole line
Where have I gone wrong? Was I far off?
Greatly appreciated, thank you!
Something like this
if flag == 0:
print(search, "Not Found")
else:
print(search, 'find in line N° ', index , ' line:',line )
StockFile.close()
Alternatively you could open your file using a context manager. This will automatically handle closing the file, here's an example:
def lookupstock():
flag = False
with open('file.txt', 'r') as StockFile:
search = str(input("Please enter in the Item: "))
for index, line in enumerate(StockFile):
if search in line:
print(line, f"Found at line {index}")
flag = True
if not flag:
print(search, "Not Found")
lookupstock()
Results:
Please enter in the Item: test
test Not Found
Please enter in the Item: hello
hello Found at line 0
Setting flags, breaking the loop then testing the flag is not good practice - it's unnecessarily complex. Try this instead:
def LookupStock():
search = input('Enter search item: ')
with open('file.txt') as StockFile:
for line in StockFile:
if search in line:
print(line)
break
else:
print(search, ' not found')

any way to print a specific string based off of a line of a file?

so I'm currently trying to print a list of cards in a text based card battler I'm making for a school project, and I'm wondering if I can get some help. I'm trying to print something different if a line in a file is 0 or 1, but I can't figure it out. thanks if you can help
def mainfunc():
while i<cardlist:
#if it's zero, do this
print("the card this line represents")
#if it's one, do this
print("locked")
#else, becasue if it's else then you're at the end of the file
print("your deck:")
#print your current deck
print("which card do you want to add?")
print(filelinecount("RIPScards"))
This is what I would do (UPDATED):
# For preventing unwanted behavior if this file ever gets imported in another:
if __name__ == "__main__":
with open(**insert file path here**, 'r') as f:
for line in f:
if line.strip() == "0":
print("the card this line represents")
elif line.strip() == "1":
print("locked")
else:
print("your deck")
print("which card do you want to add?")
print(filelinecount("RIPScards"))
You can read a file line-by-line with it open like so:
with open(**file path**, 'r') as f:
for line in f:
# Do stuff with the line here
Or you can read all the lines one time and close the file, then do stuff with the lines, like so:
f = open(**file name here**, 'r')
$lines = f.readlines()
f.close() # Make sure to close it, 'with open' method automatically does that for you, but manually opening it (like in this example) will not do it for you!
# Do stuff with it:
for line in lines:
# Do something with the line
Hopefully that helps!

Issue with conditional statement on external python file

I created this script that could be used as a login, and then created an external text file that has the data 1234 in it, this is attempting to compare the data from the file, but outputs that the two values are different, even though they are the same. Thanks In advance to any help you can give me, the code I used is below:
getUsrName = input("Enter username: ")
file = open("documents/pytho/login/cdat.txt", "r")
lines = file.readlines()
recievedUsrName = lines[1]
file.close()
print(getUsrName)
print(recievedUsrName)
if recievedUsrName == getUsrName:
print("hello")
elif getUsrName != recievedUsrName:
print("bye")
else:
Try it like:
if recievedUsrName.strip() == getUsrName:
...
It must be the trailing newline.

Python: Writing to file using for loop

Using this Python code I get printed lines of file in UPPERCASE but file remains unchanged (lowercase.)
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
fhand=open(fname, "r+")
break
except:
print "WRONG!!!"
continue
else: exit()
return fhand
fhand=open_f()
for line in fhand:
ss=line.upper().strip()
print ss
fhand.write(ss)
fhand.close()
Can you suggest please why files remain unaffected?
Code:
def file_reader(read_from_file):
with open(read_from_file, 'r') as f:
return f.read()
def file_writer(read_from_file, write_to_file):
with open(write_to_file, 'w') as f:
f.write(file_reader(read_from_file))
Usage:
Create a file named example.txt with the following content:
Hi my name is Dmitrii Gangan.
Create an empty file called file_to_be_written_to.txt
Add this as the last line file_writer("example.txt", "file_to_be_written_to.txt") of your .py python file.
python <your_python_script.py> from the terminal.
NOTE: They all must be in the same folder.
Result:
file_to_be_written_to.txt:
Hi my name is Dmitrii Gangan.
This program should do as you requested and allows for modifying the file as it is being read. Each line is read, converted to uppercase, and then written back to the source file. Since it runs on a line-by-line basis, the most extra memory it should need would be related to the length of the longest line.
Example 1
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell() # remember beginning of line
line = file.readline() # get the next available line
if not line: # check if at end of the file
break # program is finished at EOF
file.seek(position) # go back to the line's start
file.write(line.upper()) # write the line in uppercase
def get_file(prompt):
while True:
try: # run and catch any error
return open(input(prompt), 'r+t') # r+t = read, write, text
except EOFError: # see if user if finished
raise SystemExit() # exit the program if so
except OSError as error: # check for file problems
print(error) # report operation errors
if __name__ == '__main__':
main()
The following is similar to what you see up above but works in binary mode instead of text mode. Instead of operating on lines, it processes the file in chunks based on the given BUFFER_SIZE and can operate more efficiently. The code under the main loop may replace the code in the loop if you wish for the program to check that it is operating correctly. The assert statements check some assumptions.
Example 2
BUFFER_SIZE = 1 << 20
def main():
with get_file('Enter filename: ') as file:
while True:
position = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
file.seek(position)
file.write(buffer.upper())
# The following code will not run but can replace the code in the loop.
start = file.tell()
buffer = file.read(BUFFER_SIZE)
if not buffer:
return
stop = file.tell()
assert file.seek(start) == start
assert file.write(buffer.upper()) == len(buffer)
assert file.tell() == stop
def get_file(prompt):
while True:
try:
return open(input(prompt), 'r+b')
except EOFError:
raise SystemExit()
except OSError as error:
print(error)
if __name__ == '__main__':
main()
I suggest the following approach:
1) Read/close the file, return the filename and content
2) Create a new file with above filename, and content with UPPERCASE
def open_f():
while True:
fname=raw_input("Enter filename:")
if fname != "done":
try:
with open(fname, "r+") as fhand:
ss = fhand.read()
break
except:
print "WRONG!!!"
continue
else: exit()
return fname, ss
fname, ss =open_f()
with open(fname, "w+") as fhand:
fhand.write(ss.upper())
Like already alluded to in comments, you cannot successively read from and write to the same file -- the first write will truncate the file, so you cannot read anything more from the handle at that point.
Fortunately, the fileinput module offers a convenient inplace mode which works exactly like you want.
import fileinput
for line in fileinput.input(somefilename, inplace=True):
print(line.upper().strip())

inputting a words.txt file python 3

I am stuck why the words.txt is not showing the full grid, below is the tasks i must carry out:
write code to prompt the user for a filename, and attempt to open the file whose name is supplied. If the file cannot be opened the user should be asked to supply another filename; this should continue until a file has been successfully opened.
The file will contain on each line a row from the words grid. Write code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.After the input is complete the grid should be displayed on the screen.
Below is the code i have carried out so far, any help would be appreciated:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
except IOError as e:
print ("File Does Not Exist")
Note: Always avoid using variable names like file, list as they are built in python types
while True:
filename = raw_input(' filename: ')
try:
lines = [line.strip() for line in open(filename)]
print lines
break
except IOError as e:
print 'No file found'
continue
The below implementation should work:
# loop
while(True):
# don't use name 'file', it's a data type
the_file = raw_input("Enter a filename: ")
try:
with open(the_file) as a:
x = [line.strip() for line in a]
# I think you meant to print x, not a
print(x)
break
except IOError as e:
print("File Does Not Exist")
You need a while loop?
while True:
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
print (a)
break
except IOError:
pass
This will keep asking untill a valid file is provided.

Categories

Resources