Put numbers in a txt file - python

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")

Related

Terminal in PyChram not showing me an output

This is my test code, but I have a more elaborate one - but they both don't work. In python 3.x.
import sys
def main():
inputfile = 'hi'
print(inputfile)
if __name__ == '__main__':
main()
EDIT: This what I want to use the terminal for (and syntax errors - same problem):
import csv
import sys
import json
inputfile = sys.argv[1]
outputfile = sys.argv[2]
# reading the csv
with open(inputfile, 'r') as inhandle: # r is reading while w is writing
reader = csv.DictReader(inhandle)
data = []
for row in reader:
data.append(row)
print(data)
# writing the json
with open(outputfile, "W") as outhandle:
json.dump(data, outhandle, indent=2)
As far as I understood by the code you've attached, hi must be wrote as 'hi'. In your original code, hi is regarded as another variable being assigned to inputfile, but it's not defined yet.

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

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

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

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))

how to create file names from a number plus a suffix in python

how to create file names from a number plus a suffix??.
for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite.
no matter what name is generated from the first program. the second program of be taken exactly from the path and file name that was assigned to continue the script.
thanks for your help and attention
As far as I can understand you, you want to create a file with a unique name in one program and pass the name of that file to another program. I think you should take a look at the tempfile module, http://docs.python.org/library/tempfile.html#module-tempfile.
Here is an example that makes use of NamedTemporaryFile:
import tempfile
import os
def produce(text):
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(text)
return f.name
def consume(filename):
try:
with open(filename) as f:
return f.read()
finally:
os.remove(filename)
if __name__ == '__main__':
filename = produce('Hello, world')
print('Filename is: {0}'.format(filename))
text = consume(filename)
print('Text is: {0}'.format(text))
assert not os.path.exists(filename)
The output is something like this:
Filename is: /tmp/tmpp_iSrw.txt
Text is: Hello, world

Categories