I was looking around but I couldn't find a question similar that also includes functions.
My PYTHON code is supposed to output every line in a text file, but in uppercase. I understand how you'd do this without functions, but I have to use a function.
It prints out everything in uppercase, but the first line, I think its because of the f.read ?? I've played around with it, but then it just outputs nothing. I also tried a different method, but it created an entirely new file, and that's not the result I need. Any ideas on how to go about this?
Here's what I did
def uppercase():
with open("qwerty.txt", "r") as f:
for line in f:
line = f.read()
line = line.upper()
return line
print(uppercase())
You don't need to do line = f.read() since you're already getting the line with your loop variable. This is why your program doesn't output the first line.
Moreover, the return is outside the loop so that means you will only return the last value of line. My guess is that your function should directly print all the lines in uppercase, it's ok if it returns nothing.
So basically, you should end up with a function like this:
def uppercase(file):
with open(file, "r") as f:
for line in f:
line = line.upper()
print(line)
uppercase("query.txt")
Related
I am trying to read the text within a .m file in Python and Python keeps reading a single character within the .m file as a line when I use file.readline(). I've also had issues with trying to remove certain parts of the line before adding it to a list.
I've tried adjusting where the readline is on for loops that I have set up since I have to read through multiple files in this program. No matter where I put it, the string always comes out separated by character. I'm new to Python so I'm trying my best to learn what to do.
# Example of what I did
with open('MyFile.m') as f:
for line in f:
text = f.readline()
if text.startswith('%'):
continue
else:
my_string = text.strip("=")
my_list.append(my_string)
This has only partially worked as it will still return parts of lines that I do not want and when trying to format the output by putting spaces between new lines it output like so:
Expected: "The String"
What happened: "T h e S t r i n g"
Without your input file I've had to make some guesses here
Input file:
%
The
%
String
%
Solution:
my_list = []
with open('MyFile.m') as f:
for line in f:
if not line.startswith('%'):
my_list.append(line.strip("=").strip())
print(' '.join(my_list))
The readLine() call was unnecessary as the for loop already gets you the line. The empty if was negated to only catch the part that you cared about. Without your actual input file I can't help with the '=' part. If you have any clarifications I'd be glad to help further.
As suggested by Xander, you shouldn't call readline since the for line in f does that for you.
my_list = []
with open('MyFile.m') as f:
for line in f:
line = line.strip() # lose the \n if you want to
if line.startswith('%'):
continue
else:
my_string = line.strip("=")
my_list.append(my_string)
I would like to pass 1 or more parameters from a text file to a python function using a batch file. Is this possible? Ideally I would like to read from a line in the text file which would pass the specific com port to the python function, my_function and these actions could be done using a batch file
I can currently call a python script using a batch file as shown below. Separately I can also call a python function and pass a parameter to it using Python Shell. I need to be able to pass different values from a text file to the same function which is where I'm stuck.
Any help would be greatly appreciated.
Current batch file code calling a python script
echo[
#echo. The Step below calls the script which opens COM 12
echo[
"C:\Python\python.exe" "C:\Scripts\open_COM12.py"
Current python code to pass parameter (com port number) and call python function
import ConfigComPort as cw
from ConfigComPort import my_function
my_function('12')
Connection successfully made
Text File contents
COM_PORTS
12
19
23
22
If you have a file called parameters.txt with data
foo
bar
foobar
And a function
def my_function(some_text):
print("I was called with " + some_text)
Then you can do this to pass every line of the file to the function:
with open('parameters.txt', 'r') as my_file:
for line in my_file:
# remove the # and space from the next line to enable output to console:
# print(line.rstrip())
my_function(line.rstrip())
Note that the rstrip() method in all my examples strips off the trailing newline (as well as other trailing whitespace) that would otherwise be part of each line.
If your parameter file has a header, as in your example, you have multiple possibilities to skip that.
For example you can read all lines at once into a list and then iterate over a subset:
with open('parameters.txt', 'r') as my_file:
all_lines = [line.rstrip() for line in my_file.readlines()]
# print(all_lines)
for line in all_lines[1:]:
# print(line)
my_function(line)
However, that would just ignore the header. If you accidentally passed a wrong file or one that has invalid content, this could spell trouble.
It's better to check whether the header of the file is correct. You can just expand the code from above:
with open('parameters.txt', 'r') as my_file:
all_lines = [line.rstrip() for line in my_file.readlines()]
# print(all_lines)
if all_lines[0] != 'COM_PORTS':
raise RuntimeError("file has wrong header")
for line in all_lines[1:]:
# print(line)
my_function(line)
Or you can do this inside the loop, for instance:
expect_header = True
with open('parameters.txt', 'r') as my_file:
for line in my_file:
stripped = line.rstrip()
if expect_header:
if stripped != 'COM_PORTS':
raise RuntimeError("header of file is wrong")
expect_header = False
continue
# print(stripped)
my_function(stripped)
Or you can use an generator expression to check the header outside of the loop:
with open('parameters.txt', 'r') as my_file:
all_lines = (line.rstrip() for line in my_file.readlines())
if next(all_lines) != 'COM_PORTS':
raise RuntimeError("file has wrong header")
for line in all_lines:
# print(line)
my_function(line)
I would likely prefer this last one, as it is has a clear structure and no magic numbers (such as 0 and 1, referring to which line is the header and how many to skip, respectively) and it doesn't need to read all lines into memory at once.
However, the solution further above that reads all lines into a list at once is probably better if you want to do further processing on them as the data is already available in that case and you don't need to read the file again.
Im trying to print palindrome words in a file (where each line is a word) in python.
Thats what I have so far:
I have to work in Unix so I wrote my script in file palindrome.py as below:
#!/usr/bin/python
def isPalindrome(a):
if a == a[::-1]:
print a
with open ('fileName') as f:
for line in f:
isPalindrome(line)
When I run the file it doesn't print anything even-though there are palindrome words in my file. I think the problem is related to my function call because if instead of isPalindrome(line) I have isPalindrome('aha') it will print aha. I tried to print each line after the for loop but that works as well. It does print all the lines of the file. So line does get different values so I guess there might be something related to the call but I am failing to find out what.
You need to strip newlines from the end of your lines. Try call as isPalindrome(line.strip()).
Attention: file.readlines() does not wrap end line characters!!
so if in you file you have aha in one line, the line will be aha\n (with the new line char...)...
I suggest use of replace() string method.
Your code:
#!/usr/bin/python
def isPalindrome(a):
if a == a[::-1]:
print a
with open ('fileName') as f:
for line in f:
isPalindrome(line.replace('\n', '').replace("\r", "")) # replace carriage return / line feed chars
As a practice, I am learning to reading a file.
As is obvious from code, hopefully, I have a file in working/root whatever directory. I need to read it and print it.
my_file=open("new.txt","r")
lengt=sum(1 for line in my_file)
for i in range(0,lengt-1):
myline=my_file.readlines(1)[0]
print(myline)
my_file.close()
This returns error and says out of range.
The text file simply contains statements like
line one
line two
line three
.
.
.
Everything same, I tried myline=my_file.readline(). I get empty 7 lines.
My guess is that while using for line in my_file, I read up the lines. So reached end of document. To get same result as I desire, I do I overcome this?
P.S. if it mattersm it's python 3.3
No need to count along. Python does it for you:
my_file = open("new.txt","r")
for myline in my_file:
print(myline)
Details:
my_file is an iterator. This a special object that allows to iterate over it.
You can also access a single line:
line 1 = next(my_file)
gives you the first line assuming you just opened the file. Doing it again:
line 2 = next(my_file)
you get the second line. If you now iterate over it:
for myline in my_file:
# do something
it will start at line 3.
Stange extra lines?
print(myline)
will likely print an extra empty line. This is due to a newline read from the file and a newline added by print(). Solution:
Python 3:
print(myline, end='')
Python 2:
print myline, # note the trailing comma.
Playing it save
Using the with statement like this:
with open("new.txt", "r") as my_file:
for myline in my_file:
print(myline)
# my_file is open here
# my_file is closed here
you don't need to close the file as it done as soon you leave the context, i.e. as soon as you continue with your code an the same level as the with statement.
You can actually take care of all of this at once by iterating over the file contents:
my_file = open("new.txt", "r")
length = 0
for line in my_file:
length += 1
print(line)
my_file.close()
At the end, you will have printed all of the lines, and length will contain the number of lines in the file. (If you don't specifically need to know length, there's really no need for it!)
Another way to do it, which will close the file for you (and, in fact, will even close the file if an exception is raised):
length = 0
with open("new.txt", "r") as my_file:
for line in my_file:
length += 1
print(line)
I am a beginner and just started learning Python couple days ago (yay!)
so i've come across a problem. when i run, this code outputs everything but the text (txt in file is numbers 0-10 on seperate lines)
def output():
xf=open("data.txt", "r")
print xf
print("opened, printing now")
for line in xf:
print(xf.read())
print("and\n")
xf.close()
print("closed, done printing")
You don't use line, try:
with open('data.txt') as f:
for line in f:
print line
This should print out each number on its own line, like you want, in a lot less code, and more readable.
def output():
f = open('data.txt', 'r').read()
print f
When you used for line in xf: you basically already iterated over the file, implicitly reading each line.
All you need to do is print it:
for line in xf:
print(line)
The reason you aren't seeing the line output is because you aren't telling it to output the line. While iterating over values of line, you print xf.read(). The following is your function rewritten with this in mind. Also added is the use of a with statment block to automatically close the file when you're done with it.
(Using xf.close() is not wrong, just less pythonic for this example.)
def output():
with open("data.txt", "r") as xf:
print xf
print("opened, printing now")
for line in xf:
print(line)
print("and\n")
print("closed, done printing")
You have read the line of text into the variable line in the code for line in xf: so you need to show that e.g. print(line)
I would look at tutorials like the python.org one