Why is idle skipping over f = open('filename' , 'r') - python

I'm writing a program in python and I am having issues getting idle to read my file out. If I use improper syntax it tells me, so it is being read by the compiler but not printing it for the user. Any help would be appreciated. Here is my code.
#! python3.5.2
import sys
if input() == ('im bored'):
print('What season is it?')
if input() == ('summer'):
f = open('callfilesummer.txt', 'r')

You only put file into variable 'f', so you need to read it or work it with someway to show it.
import sys
if input() == ('im bored'):
print('What season is it?')
if input() == ('summer'):
f = open('callfilesummer.txt', 'r')
print f.read()
f.close()
You can find more way how to work with files on this http://www.tutorialspoint.com/python/python_files_io.htm

This doesn't do anything. Maybe take a look at the Python documentation? https://docs.python.org/3/tutorial/inputoutput.html
That's a start.
If you want to display the file, you can very easily iterate over a file in Python like this:
f = open('hurdurr', 'r')
for line in f:
print line

Related

How to make python code read a certain line of text in a .txt file?

So i have been fiddling around with python and league of legends. And i found out you can make notes in game. So i thought about making python code read a line of text from the note i made in game, like "Lux no flash", but it doesn't seems to be able to read it at all, it only works when i do it manually with the exact same code. Here is my code:
import os
import time
def main():
os.chdir('C:\\Riot Games\\League of Legends\\RADS\\solutions\\lol_game_client_sln\\releases\\0.0.1.237')
f=open("MyNotes.txt", "r")
if f.mode == 'r':
lines=f.readlines()
text = lines[4]
time.sleep(0.1)
if text == 'Lux no flash':
print('Done')
else:
print('Something went wrong')
f.close()
if __name__== "__main__":
main()
The output is "something went wrong", but when i do it manually it says "done". I feel like python cant read league code. Maybe you guys know how to do this... This is the .txt file im trying to access:
##################################################
2018-09-13_18-57-33_
##################################################
Lux no flash
Using lux.txt:
##################################################
2018-09-13_18-57-33_
##################################################
Lux no flash
Code:
content = []
with open('lux.txt', 'r') as f:
for line in f:
content.append(line.strip('\n'))
for i in content:
if 'Lux no flash' == i:
print("Done")
else:
pass
Better #pygo
with open('lux.txt', 'r') as f:
content = f.read()
if 'Lux no flash' in content:
print("Done")
else:
print("No else, this works :)")
Output:
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 lux.py
Done
I'm Just taking a file on an assumption basis:
# cat MyNotes.txt
there is Lux no flash in line
there is Something went wrong
There is nothing lux no flash
this is all test
So, just looking for the word 'Lux no flash' you are searching into your file, we can simply do as below.. but its case sensitive.
It's always best practice to use with open() method to read a file.
import os
import time
def main():
with open("MyNotes.txt") as f:
for line in f.readlines():
if 'Lux no flash' in line:
print('Done')
else:
print('Something went wrong')
if __name__== "__main__":
main()
Output result will be :
Done
Something went wrong
Something went wrong
Something went wrong
Even tried using the lux.txt , it works as expected with my code.
import os
import time
def main():
with open("lux.txt") as f:
for line in f.readlines():
#line = line.strip() # use can use the strip() or strip("\n")
#line = line.strip("\n") # if you see white spaces in the file
if 'Lux no flash' in line:
print('Done')
else:
pass
if __name__== "__main__":
main()
Resulted outout is:
# test.py
Done

Put numbers in a txt file

I am trying to put the output of these numbers into a file but I am failing a bit.
This is my code so far :
import os
import sys
with open('somefile.txt', 'rt') as f:
print('Hello World!')
os.system("pause")
num = int(input("Display multiplication table of? "))
for i in range(1,1000001):
print(num*i, file=f)
os.system("pause")
The programm says the = at file=f has a syntax error. Any1 know why?
Two things you did wrong:
- Didn't have f defined when you wrote to the file
- Didn't have the file opened as a write - you had it open as a read
After fixing them, the code executed perfectly!
import os
import sys
f = open('somefile.txt', 'wt') # CHANGED LINE
print('Hello World!')
os.system("pause")
num = int(input("Display multiplication table of? "))
for i in range(1,1000001):
print(num*i, file=f)
os.system("pause")

Read file-names with extensions into python

I am trying to read a filename that has a period in it, into this simple program..
files like "test" work, while test.txt fail.
I kinda see why. when I type in "test.txt", only "test" appears.
when I use quotes, I get:
IOError: [Errno 2] No such file or directory: "'test.txt'"
is there a simple way I can read file names that have things like extensions?
#!/usr/bin/python
#File Attributes
fn=input("Enter file Name: ")
print (fn) #added so i know why its failing.
f = open(`fn`,'r')
lines = f.read()
print(lines)
f.close()
Using the with...as method as stated in this post:
What's the advantage of using 'with .. as' statement in Python?
seems to resolve the issue.
Your final code in python3 would look like:
#!/usr/bin/python
#File Attributes
fn = input("Enter file Name: ")
with open(fn, 'r') as f:
lines = f.read()
print(lines)
In python2 *input("")** is replaced by raw_input(""):
#!/usr/bin/python
#File Attributes
fn = raw_input("Enter file Name: ")
with open(fn, 'r') as f:
lines = f.read()
print(lines)
I would do it the following way:
from os.path import dirname
lines = sorted([line.strip().split(" ") for line in open(dirname(__file__) + "/test.txt","r")], key=lambda x: x[1], reverse=True)
print [x[0] for x in lines[:3]]
print [x[0] for x in lines[3:]]
You use the input function, this built_in function need a valid python input, so you can try this:
r'test.txt'
But you have to make sure that the test.txt is a valid path. I just try your code, I just change the open function to:
f = open(fn,'r')
and input like this:
r'C:\Users\Leo\Desktop\test.txt'
it works fine.

I want to create a program that reads text file

it does work if I type this on python shell
>>> f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
>>> f.read()
'plpw eeeeplpw eeeeplpw eeee'
>>> f.close()
but if I create a python program, i doesn't work.
import os
f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
f.read()
f.close()
i saved this piece of code by using text editor.
if I execute this program in python shell, it shows nothing.
please tell me why..
In the interactive prompt, it automatically prints anything a function call returns. That means the return value of f.read() is printed automatically. This won't happen when you put it in a program however, so you will have to print it yourself to have it show up.
import os
f = open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
print f.read() # use print(f.read()) in Python 3
f.close()
Another suggestion I would make would be to use a with block:
import os
with open(os.path.join(os.getcwd(), 'test1.txt'), 'r') as f:
print f.read()
This means that you won't have to worry about manually closing the file afterwards.

select multiple files. python

I have created this search and replace program.
But I want to make changes to it, so I can do a search and replace for
multiple files at once.
Now, is there a way so I have
the option to select multiple files at once
from any folder or directory that I choose.
The code that helps me to select files using file dialog window is given below, but is giving errors. can you help me to correct it?
The FULL traceback error is :
Traceback <most recent call last>:
File "replace.py", line 24, in <module>
main()
File "replace.py", line 10, in main
file = tkFileDialog.askopenfiles(parent=root,mode='r',title='Choose a file')
File "d:\Python27\lib\lib-tk\tkFileDialog.py",line 163, in askopenfiles
ofiles.append(open(filename,mode))
IOError: [Errno 2] No such file or directory: u'E'
And here's the code: I finally got this code to work I changed 'file' to 'filez' and 'askopenfiles' to askopenfilenames'. and I was able to replace the word in my chosen file. the only thing is that it doesnt work when I choose 2 files. maybe I should add in a loop for it to work for multiple files. But, this was a kind of trial and error and I want to be able to really know why it worked. Is there a book or something that will help me to fully understand this tkinter and file dialog thing? anyways, I have changed the code below to show the working code now:
#replace.py
import string
def main():
#import tkFileDialog
#import re
#ff = tkFileDialog.askopenfilenames()
#filez = re.findall('{(.*?)}', ff)
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,mode='r',title='Choose a file')
#filez = raw_input("which files do you want processed?")
f=open(filez,"r")
data=f.read()
w1=raw_input("what do you want to replace?")
w2= raw_input("what do you want to replace with?")
print data
data=data.replace(w1,w2)
print data
f=open(filez,"w")
f.write(data)
f.close()
main()
EDIT: One of the replies below gave me an idea about file dialog window and now I am able to select multiple files using a tkinter window, but I am not able to go ahead with the replacing. it's giving errors.
I tried out different ways to use file dialog and the different ways are giving different errors. Instead of deleting one of the ways, I have just put a hash sign in front so as to make it a comment, so you guys are able to take a look and see which one would be better.
Maybe you should take a look at the glob module, it can make finding all files matching a simple pattern (such as *.txt) easy.
Or, easier still but less user-friendly, you could of course treat your input filename filez as a list, separating filenames with space:
for fn in filez.split():
# your code here, replacing filez with fn
You probably want to have a look at glob module.
An example that handles "*" in your input:
#replace.py
import string
import glob
def main():
filez = raw_input("which files do you want processed?")
filez_l = filez.split()
w1=raw_input("what do you want to replace?")
w2= raw_input("what do you want to replace with?")
# Handle '*' e.g. /home/username/* or /home/username/mydir/*/filename
extended_list = []
for filez in filez_l:
if '*' in filez:
extended_list += glob.glob(filez)
else:
extended_list.append(filez)
#print extended_list
for filez in extended_list:
print "file:", filez
f=open(filez,"r")
data=f.read()
print data
data=data.replace(w1,w2)
print data
f=open(filez,"w")
f.write(data)
f.close()
main()
I would rather use the command line instead of input.
#replace.py
def main():
import sys
w1 = sys.argv[1]
w2 = sys.argv[2]
filez = sys.argv[3:]
# ***
for fname in filez:
with open(fname, "r") as f:
data = f.read()
data = data.replace(w1, w2)
print data
with open(fname, "w") as f:
f.write(data)
if __name__ == '__main__':
main()
So you can call your program with
replace.py "old text" "new text" *.foo.txt
or
find -name \*.txt -mmin -700 -exec replace.py "old text" "new text" {} +
If you think of a dialog window, you could insert the following at the position with ***:
if not filez:
import tkFileDialog
import re
ff = tkFileDialog.askopenfilenames()
filez = re.findall('{(.*?)}', ff)
Why not put the program into a for-loop:
def main():
files = raw_input("list all the files do you want processed (separated by commas)")
for filez in files.split(','):
f=open(filez,"r")
data=f.read()
f.close()
w1=raw_input("what do you want to replace?")
w2= raw_input("what do you want to replace with?")
print data
data=data.replace(w1,w2)
print data
f=open(filez,"w")
f.write(data)
f.close()
main()
A good trick to open huge files line by line in python:
contents = map(lambda x: x.next().replace("\n",""),map(iter,FILES))

Categories