I'm wondering if it's possible to use the return from raw_input()
to create a file name?
What I have so far:
import os
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
ttnum=str(raw_input('Please enter ticket number: '))
ttnum
filename=askopenfilename()
abspath = os.path.abspath(filename)
dname = os.path.dirname(abspath)
os.chdir(dname)
f=open(filename)
contents=f.read()
file_len(filename)
file_scan(filename)
Portion of code that calls ttnum:
def file_len(filename):
#Count the number of line in the Text File
f1 = open(("WiFi Logs report for tt " + ttnum,'w'))
with open(filename) as f:
for i, l in enumerate(f):
pass
f1.write('Total number of lines in file: ' + str(i+1) + '\n' + '\n')
f1.close()
def file_scan(filename):
#List of issues to Scan For
f1 = open(("WiFi Logs report for tt " + ttnum,'a'))
I can enter input no problem (in this case 12345), but once it hits the code, I get the following:
Traceback (most recent call last):
File "M:\WiFi Log Scanner\WiFi_Log_Scanner.py", line 153, in <module>
file_len(filename)
File "M:\WiFi Log Scanner\WiFi_Log_Scanner.py", line 4, in file_len
f1 = open(("WiFi Logs report for tt " + ttnum,'w'))
TypeError: coercing to Unicode: need string or buffer, tuple found
I thought that the str() at the start would ensure that it is, well, a string and not a tuple?
Any insight would be appreciated.
Thanks,
Joe
Remove a layer of parentheses from open(("WiFi Logs report for tt " + ttnum,'a'))
:
open("WiFi Logs report for tt " + ttnum,'a')
With extra parentheses, you pass one argument to open
, and this argument is a tuple: a pair of values, which is not what open
expects for its first argument.
A side note (unrelated to your error): you don't have to chdir
before you read a file (and your actual code only works when filename
is already absolute, which the result of tk_getOpenFile
is. chdir
doesn't help anything here). And when chdir
is necessary, it's error-prone (it introduces hidden state) and thread-unsafe.