text - using txt file as input for python -
i have python program requires user paste text process da various tasks. this:
line=(input("paste text here: ")).lower()
the pasted text comes .txt file. avoid issues code (since text contains multiple quotation marks), user has following: type 3 quotation marks, paste text , type 3 quotation marls again.
can of above avoided having python read .txt? , if so, how?
please let me know if question makes sense.
in python2, use raw_input receive input string. no quotation marks on part of user necessary.
line=(raw_input("paste text here: ")).lower()
note input equivalent
eval(raw_input(prompt))
and applying eval
user input dangerous, since allows user evaluate arbitrary python expressions. malicious user delete files or run arbitrary functions never use input
in python2!
in python3, input
behaves raw_input
, there code have been fine.
if instead you'd user type name of file, then
filename = raw_input("text filename: ") open(filename, 'r') f: line = f.read()
troubleshooting:
ah, using python3 see. when open file in r
mode, python tries decode bytes
in file str
. if no encoding specified, uses locale.getpreferredencoding(false)
default encoding. apparently not right encoding file. if know encoding file using, best supply encoding
parameter:
open(filename, 'r', encoding=...)
alternatively, hackish approach not satisfying ignore decoding errors:
open(filename, 'r', errors='ignore')
a third option read file bytes:
open(filename, 'rb')
of course, has obvious drawback you'd dealing bytes \x9d
rather characters ·
.
finally, if you'd guessing right encoding file, run
with open(filename, 'rb') f: contents = f.read() print(repr(contents))
and post output.
Comments
Post a Comment