I am getting a TypeError: object of type file' has no len()
I have traced down the issue to the path established upon execution.
What am I missing to correct this error found within the "savePath" deceleration or usage within the "temp = os.path.join(savePath, files)"?
def printTime(time):
savePath = "C:\Users\Nicholas\Documents"
files = open("LogInLog.txt", "a")
temp = os.path.join(savePath, files)
files.write("A LogIn occured.")
files.write(time)
print files.read
files.close
main()
The whole program is below for reference:
from time import strftime
import os.path
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = "C:\Users\Nicholas\Documents"
files = open("LogInLog.txt", "a")
temp = os.path.join(savePath, files)
files.write("A LogIn occured.")
files.write(time)
print files.read
files.close
main()
Here's a working version:
from time import strftime
import os.path
def main():
getTime()
def getTime():
time = strftime("%Y-%m-%d %I:%M:%S")
printTime(time)
def printTime(time):
savePath = "C:\Users\Nicholas\Documents"
logFile = "LogInLog.txt"
files = open(os.path.join(savePath, logFile), "a+")
openPosition = files.tell()
files.write("A LogIn occured.")
files.write(time)
files.seek(openPosition)
print(files.read())
files.close()
if __name__ == '__main__':
main()
There were a few problems with the code snippet posted in the question:
Two import statements were concatenated together. Each should be on a separate line.
The os.path.join function doesn't work on an open filehandle.
The read() and close() methods were missing parens.
If the intent is to read what is written in append mode, it's necessary to get the current file position via tell() and seek() to that position after writing to the file.
While it's legal to call main() without any conditional check, it's usually best to make sure the module is being called as a script as opposed to being imported.
Related
I've got a script that is intended to sort my photo/video collection (Windows). The photos work fine as they are sortable by EXIF which is easily accessed.
Videos are harder because I have to get the file's "Media Creation Date" which is readable by only pywin32, to my understanding. However, once I've accessed the media creation date, shutil.move() does not work. It throws no error, it just runs indefinitely without progress until I manually kill the script:
Here's the snippet in question:
from datetime import datetime
import exifread
import os
from pathlib import Path
import shutil
from win32com.propsys import propsys, pscon
# get the file list, do stuff with photos, etc
# f is the file
# cr is the path root to which it will be moved
elif str(f).lower().endswith(("mp4", "mov")):
props = propsys.SHGetPropertyStoreFromParsingName(f)
dt = props.GetValue(pscon.PKEY_Media_DateEncoded).GetValue()
year, month = str(dt.year), str(dt.month).zfill(2)
new_fn = dt.strftime("%Y-%m-%d_%H%M%S")
new_fn = f"{new_fn}{os.path.splitext(f)[1]}"
move_path = os.path.join(cr, year, month, new_fn)
print(f"SRC: {f}")
print(f"DESTINATION: {move_path}")
print("----------------------------------")
shutil.move(f, move_path)
It prints the source correctly, and the destination correctly, but does not move the file. I have also tried os.rename() and os.replace() with the same result, which suggests that perhaps the propsys method still has a lock on the file? How do I free up this file for moving?
Yes, propsys is blocking the file (you can check in Process Explorer), try just deleting it:
fpath = r'c:\temp\user\t\test.mp4'
move_path = r'c:\temp\user\t\test moved.mp4'
props = propsys.SHGetPropertyStoreFromParsingName(fpath)
print( props.GetValue(pscon.PKEY_Media_DateEncoded).GetValue() )
del props
shutil.move(fpath , move_path)
Currently, my code is like this where I upload 2 files but I need to process them in temp files via another existing parse.py file with multiple functions.
How can I call them in Templates.py?
I tried adding import parse.py but it would give an error.
templates.py
#route('/')
def index():
return template('index')
#route('/', method='POST')
def upload():
incfile = request.files.get('uploadinc')
datfile = request.files.get('uploadhex')
macro, ext1 = os.path.splitext(incfile.filename)
data, ext2 = os.path.splitext(datfile.filename)
if ext1 not in ('.txt'):
return 'File extension not allowed.'
if ext2 not in ('.txt'):
return 'File extension not allowed.'
incfile.filename = 'macro.txt'
datfile.filename = 'data.txt'
curr_dir = os.getcwd()
print(curr_dir)
temp_dir = os.path.join(curr_dir, r'temp01')
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir)
os.makedirs(temp_dir)
incfile.save(temp_dir)
datfile.save(temp_dir)
clean_up(temp_dir) // gives error
#route('/')
def clean_up(): // gives error
parse.py
import os, sys, re, binascii
def clean_up():
if os.path.exists("dataparse.txt"):
os.remove("dataparse.txt")
else:
print("Creating new files...")
if os.path.exists("out3.txt"):
os.remove("out3.txt")
else:
print("Creating new files...")
def parse_hexdump():
a = open("data.txt","r")
b = open("dataparse.txt","a")
w = open("out3.txt","a")
str = a.readline()
w.write(str)
for line in a:
if line.startswith('MD') or line.startswith('END OF DISPLAY'):
continue
else:
strline = line[5:40:] # Slice lines from 5-40 to another file
b.write(strline+'\n')
b.close()
w.close()
Just import parse, you don't put .py at the end of an import statement. Since you seem to want to just use the functions rather than calling parse.clean_up, you could instead do from parse import clean_up. The file parse needs to either be in your local directory (where you're running the python interpreter) or in your PYTHONPATH environment variable.
I'm a beginner at Python and this site. Sorry if this might be simple.
I have modified a python script that calculates the amount of words in a pdf file "Master.pdf" an writes the time and date plus the amount of words to a .txt file.
I have Python2.7 installed, I have installed Anancoda and I am using the PyCharm editor. When I open my PyCharm editor and run this script, no problems arise, the script executes and everything works.
As I would like this script to run every 15 minutes, I have made it a task using Task Scheduler. The task is "Start a program" the program is:
- C:\Users\alkare\AppData\Local\Continuum\anaconda2\python.exe - and the argument is - "C:/Users/alkare/Desktop/Report/WordCount.py" -.
whenever it runs I see the command prompt open, some text fly across my screen and then the command line terminal closes, BUT no changes are done to my .txt file.
here is the code I am using saved as "WordCount.py":
#!/usr/bin/env python2.7
import os
import sys
import re
import datetime
import PyPDF2
def getPageCount(pdf_file):
pdfFileObj = open(pdf_file, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pages = pdfReader.numPages
return pages
def extractData(pdf_file, page):
pdfFileObj = open(pdf_file, 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pageObj = pdfReader.getPage(page)
data = pageObj.extractText()
return data
def getWordCount(data):
data = data.split()
return len(data)
def main():
pdfFile = 'Master.pdf'
# get the word count in the pdf file
totalWords = 0
numPages = getPageCount(pdfFile)
for i in range(numPages):
text = extractData(pdfFile, i)
totalWords += getWordCount(text)
Now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
f = open("TrackingTimeData.txt", "a")
f.write(Now[0:4] + "\t" + Now[4:6] + "/" + Now[6:8] + "\t" + Now[9:11] + ":" + Now[11:13] + "\t" + str(totalWords) + "\n")
f.close()
if __name__ == '__main__':
main()
The problem is that you are allowing the program to fail without providing you any meaningful output (it sounds like it hits an exception and closes).
Instead of just calling main() without guarding it in a try block:
if __name__ == '__main__':
main()
give yourself some slack here to gather information:
if __name__ == '__main__':
try:
main()
except Exception as e:
print("Error {}".format(e))
# drop into a command-prompt debugger:
import pdb
pdb.set_trace()
# slightly more old-school, pause the window to read the exception:
import time
time.sleep(15)
# throwback to DOS windows
import os
os.system('pause')
# read the error, come back to stackoverflow and describe the problem more, etc.
For example, mixing this with task scheduler, you'd want to right-click on your python.exe in Windows, go to properties, set "Run as Administrator" because maybe you're getting an access denied trying to read/write to a .PDF in some special directory. This is just an example of the many guesses people could throw in to randomly help you solve an issue versus knowing exactly what the error is.
I tried writing my own script in Python that takes the output from the "iplist" variable and prints it to a text file, however I'm stuck as to why the script will create the file but not print anything? I've been stuck on this for a day now, and nothing I've found online has seemed to help me :/ Any pointers would be greatly appreciated!
import socket
import time as t
from os import path
def ip_list(dest):
iplist = socket.gethostbyname_ex(socket.gethostname())
date = t.localtime(t.time())
name = "IP addresses on %d_%d_%d.txt" % (date[1], date[2], date[0] % 100)
if not (path.isfile(name)):
file = open(name, 'w')
for str in iplist:
print >>f, str
f.close() ## has to match open indentation
if __name__ == '__main__':
destination = "C:\\Users\\kl\\Desktop\\python files\\"
ip_list("destination")
raw_input("Done!")
I should also add that I have attempted to use the "f.write()" command as well, not that that might be of much help?
I have a python code which opens a text file read and do some processes. The input text file has to be updated each day with a new one. Currently I use following code to open the file.
f = open('sample20130616.txt','r')
But in this method some one has to go inside the code and modify the file name(Since the file names are not unique).
What is the proper method to handle this?
Pass the filename as parameter when you call your application:
python myapp.py file.txt
Then in your code:
import sys
if __name__ == '__main__':
filename = sys.argv[1]
f = open(filename)
You can easily generate the current date and hence your filename with the datetime module:
import datetime
today = datetime.date.today()
filename = 'sample{0}{1:02d}{2:02d}.txt'.format(today.year, today.month, today.day)
f = open(filename,'r')
Use the built-in time function!
from time import gmtime, strftime
fname='sample'+strftime("%Y%m%d", gmtime())+'.txt'
f = open(fname,'r')