File in and file out in python - python

i had created a python program but it was not working. this program would take in the input for a file and then display the file contents . the only error i was getting is a syntax error well i could not find the error . Please help me .
the code was :-
nm = input(“enter file name “)
str = raw_input(“enter ur text here: \n”)
f = open(nm,”w”)
f.write(str)
f.close()
print “1.See the file\n”
print “2.Exit\n”
s = input(“enter ur choice “)
if s == 1 :
fi = open(nm,”r”)
cont = fi.read()
for i in cont:
print i
else :
print “thank you “

The problem is that you are reading the filename using input() instead of raw_input(). See this answer that explains:
If you use input, then the data you type is is interpreted as a Python
Expression which means that you end up with gawd knows what type of
object in your target variable, and a heck of a wide range of
exceptions that can be generated. So you should NOT use input unless
you're putting something in for temporary testing, to be used only by
someone who knows a bit about Python expressions.
raw_input always returns a string because, heck, that's what you
always type in ... but then you can easily convert it to the specific
type you want, and catch the specific exceptions that may occur.
Hopefully with that explanation, it's a no-brainer to know which you
should use.
Also, since you are reading in the file contents by using fi.read(), your for loop for i in cont: will select each character of the file's contents one at a time, instead of each line. Something to be aware of!

Related

The open() functions doesn't behave correctly with filepath containing special characters

I'm writing this simple code:
file = input('File to read: ')
fhand = open(file, 'r')
The file I want to open is called 'test.txt', and it is located in a subfolder; what I put into the requested input therefore is: 'DB\test.txt'.
Well: it doesn't work, returning this error message:
OSError: [Errno 22]Invalid argument: 'DB\test.txt'.
I have another file in the same directory, called 'my_file.txt', and I don't get errors attempting to open it. Lastly I have another file, called 'new_file.txt', and this one also gets me the same error.
What seems obvious to me is that the open() function reads the "\t" and the "\n" as if they were special characters; searching on the web I found nothing that really could help me avoiding special characters within user input strings...
Could anybody help?
Thanks!
you'll have no problems with Python 3 with your exact code (this issue is often encountered when passing windows literal strings where the r prefix is required).
With python 2, first you'll have to wrap your filename with quotes, then all special chars will be interpreted (\t, \n ...). Unless you input r"DB\test.txt" using this raw prefix I was mentionning earlier but it's beginning to become cumbersome :)
So I'd suggest to use raw_input (and don't input text with quotes). Or python version agnostic version to override the unsafe input for python 2 only:
try:
input = raw_input
except NameError:
pass
then your code will work OK and you got rid of possible code injection in your code as a bonus (See python 2 specific topic: Is it ever useful to use Python's input over raw_input?).

Look at length of file type and determine what type of file is being opened

working on a program that takes a file and determines what type it is. It must be a .wav or .jpg file to be correct, and if it is not one of those, it will display a message that says to choose a correct file type. However, I am stuck on how to get it to determine what type of file is being chosen, since for this program I am not allowed to use f.endswith(), so I was thinking range may work but I am unsure what the paramaters should be, or if range is even the correct choice for how to determine the file type. help please :)
def fileType():
f = pickAFile
print f
for f in range ():
start = f.rfind(".")
if start!=-1:
print A .wav file type was selected
print A .jpg file type was selected
else:
print No file type was chosen
print Please choose a different file type
ok I have tried something like this but it is giving me a syntax error, could you help me with what the issue may be?
def fileType():
f = pickAFile
print f f[f.rfind('.'):]
if f[f.rfind('.'):] == '.wav':
print "A sound file was selected."
if f[f.rfind('.'):] == '.jpg' :
print "An image file was selected
else:
print " This was an incorrect file type."
print " Please chose a .wav or .jpg file."
string slicing is what you are looking for, for example:
>>> s = 'file.wav'
>>> s[s.rfind('.'):]
'.wav'
s[index:index2] returns a copy of s that starts at index and ends, but does not include, all characters to index2
you can then do a check like:
s[s.rfind('.'):] == '.wav' # this statement is == s.endswith('.wav')
using string slicing
>>> s = 'file.wav'
>>> s[-3:]
'wav'
Perhaps you can use the contains method. You would write it something like this FileVariable.contains("png"), within an if statement. These conditions would not be statements. Let me just write it out to be clear.
if (!(FileVariable.contains("fileextension"))
&& !(FileVariable.contains("otherfileextension") {
// if it makes it past this sort of filter
// then it will only be using the file types that you mention
}
You could also instead of saying each one that can't be used make a filter that tells it what can be let through. This would be much simpler.

Taking String arguments for a function without quotes

I've got a function meant to download a file from a URL and write it to a disk, along with imposing a particular file extension. At present, it looks something like this:
import requests
import os
def getpml(url,filename):
psc = requests.get(url)
outfile = os.path.join(os.getcwd(),filename+'.pml')
f = open(outfile,'w')
f.write(psc.content)
f.close()
try:
with open(outfile) as f:
print "File Successfully Written"
except IOError as e:
print "I/O Error, File Not Written"
return
When I try something like
getpml('http://www.mysite.com/data.txt','download') I get the appropriate file sitting in the current working directory, download.pml. But when I feed the function the same arguments without the ' symbol, Python says something to the effect of "NameError: name 'download' is not defined" (the URL produces a syntax error). This even occurs if, within the function itself, I use str(filename) or things like that.
I'd prefer not to have to input the arguments of the function in with quote characters - it just makes entering URLs and the like slightly more difficult. Any ideas? I presume there is a simple way to do this, but my Python skills are spotty.
No, that cannot be done. When you are typing Python source code you have to type quotes around strings. Otherwise Python can't tell where the string begins and ends.
It seems like you have a more general misunderstanding too. Calling getpml(http://www.mysite.com) without quotes isn't calling it with "the same argument without quotes". There simply isn't any argument there at all. It's not like there are "arguments with quotes" and "arguments without quotes". Python isn't like speaking a natural human language where you can make any sound and it's up to the listener to figure out what you mean. Python code can only be made up of certain building blocks (object names, strings, operators, etc.), and URLs aren't one of those.
You can call your function differently:
data = """\
http://www.mysite.com/data1.txt download1
http://www.mysite.com/data2.txt download2
http://www.mysite.com/data3.txt download3
"""
for line in data.splitlines():
url, filename = line.strip().split()
getpml(url, filename)

how can I input a file and run an asynchronously command on it in python?

I'm trying to write a script that asks for an input file and then runs some command on it. when I run the script it askes me for filename and when I give the file (e.g example.bam) then I get this error:
NameError: name 'example.bam' is not defined
I tried many things but I couldn't fix it. Can someone tell me what is wrong?
This is my comand:
from subprocess import call
filename = input ("filename: ");
with open (filename, "r") as a:
for command in ("samtools tview 'a' /chicken/chick_build2.1_unmasked.fa",):
call(command, shell=True)
This is a short version of my command: it has to do much more stuff. I'm also thinking to input 4-6 files at same time (perhaps this information is helpful to clarify my intentions).
input is equivalent to eval(raw_input(prompt)). So what your script currently tries to do is interpret your input ("example", in your case), and execute as if it were a statement in your script. For user input (and might I simply say "for any input" -- unless you know what you're doing), always use the raw_input function.
So, to solve it, replace input with raw_input:
filename = raw_input("filename: ")

Python - writing lines from file into IRC buffer

Ok, so I am trying to write a Python script for XCHAT that will allow me to type "/hookcommand filename" and then will print that file line by line into my irc buffer.
EDIT: Here is what I have now
__module_name__ = "scroll.py"
__module_version__ = "1.0"
__module_description__ = "script to scroll contents of txt file on irc"
import xchat, random, os, glob, string
def gg(ascii):
ascii = glob.glob("F:\irc\as\*.txt")
for textfile in ascii:
f = open(textfile, 'r')
def gg_cb(word, word_eol, userdata):
ascii = gg(word[0])
xchat.command("msg %s %s"%(xchat.get_info('channel'), ascii))
return xchat.EAT_ALL
xchat.hook_command("gg", gg_cb, help="/gg filename to use")
Well, your first problem is that you're referring to a variable ascii before you define it:
ascii = gg(ascii)
Try making that:
ascii = gg(word[0])
Next, you're opening each file returned by glob... only to do absolutely nothing with them. I'm not going to give you the code for this: please try to work out what it's doing or not doing for yourself. One tip: the xchat interface is an extra complication. Try to get it working in plain Python first, then connect it to xchat.
There may well be other problems - I don't know the xchat api.
When you say "not working", try to specify exactly how it's not working. Is there an error message? Does it do the wrong thing? What have you tried?

Categories

Resources