Python file open from path containing numbers - python

i have the following problem during file open:
Using PyQt QFileDialog I get path for files from user which I would like to read it
def read_file(self):
self.t_file = (QFileDialog.getOpenFileNames(self, 'Select File', '','*.txt'))
Unfortunately I cannot open a file if the path has numbers in it:
Ex:
'E:\test\02_info\test.txt'
I tried
f1 = open(self.t_file,'r')
Could anyone help me to read files from such a path format?
Thank you in advance.
EDIT:
I get the following error:
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
f1 = open(self.t_file,'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'E:\test\x02_info\test.txt'

The problem is caused by your use of getOpenFileNames (which returns a list of files) instead of getOpenFileName (which returns a single file). You also seem to have converted the return value wrongly, but since you haven't shown the relevant code, I will just show you how it should be done (assuming you are using python2):
def read_file(self):
filename = QFileDialog.getOpenFileName(self, 'Select File', '','*.txt')
# convert to a python string
self.t_file = unicode(filename)

Related

How do I write the time from datetime to a file in Python?

I'm trying to have my Python code write everything it does to a log, with a timestamp. But it doesn't seem to work.
this is my current code:
filePath= Path('.')
time=datetime.datetime.now()
bot_log = ["","Set up the file path thingy"]
with open ('bot.log', 'a') as f:
f.write('\n'.join(bot_log)%
datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
print(bot_log[0])
but when I run it it says:
Traceback (most recent call last):
File "c:\Users\Name\Yuna-Discord-Bot\Yuna Discord Bot.py", line 15, in <module>
f.write('\n'.join(bot_log)%
TypeError: not all arguments converted during string formatting
I have tried multiple things to fix it, and this is the latest one. is there something I'm doing wrong or missing? I also want the time to be in front of the log message, but I don't think it would do that (if it worked).
You need to put "%s" somewhere in the input string before string formatting. Here's more detailed explanation.
Try this:
filePath= Path('.')
time=datetime.datetime.now()
bot_log = "%s Set up the file path thingy\n"
with open ('bot.log', 'a') as f:
f.write(bot_log % datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
print(bot_log)
It looks like you want to write three strings to your file as separate lines. I've rearranged your code to create a single list to pass to writelines, which expects an iterable:
filePath= Path('.')
time=datetime.datetime.now()
bot_log = ["","Set up the file path thingy"]
with open ('bot.log', 'a') as f:
bot_log.append(datetime.datetime.now().strftime("%d-%b-%Y (%H:%M:%S.%f)"))
f.writelines('\n'.join(bot_log))
print(bot_log[0])
EDIT: From the comments the desire is to prepend the timestamp to the message and keep it on the same line. I've used f-strings as I prefer the clarity they provide:
import datetime
from pathlib import Path
filePath = Path('.')
with open('bot.log', 'a') as f:
time = datetime.datetime.now()
msg = "Set up the file path thingy"
f.write(f"""{time.strftime("%d-%b-%Y (%H:%M:%S.%f)")} {msg}\n""")
You could also look at the logging module which does a lot of this for you.

PyPDF2 IOError: [Errno 22] Invalid argument on PyPdfFileReader Python 2.7

Goal = Open file, encrypt file, write encrypted file.
Trying to use the PyPDF2 module to accomplish this. I have verified theat "input" is a file type object. I have researched this error and it translates to "file not found". I believe that it is linked somehow to the file/file path but am unsure how to debug or troubleshoot. and getting the following error:
Traceback (most recent call last):
File "CommissionSecurity.py", line 52, in <module>
inputStream = PyPDF2.PdfFileReader(input)
File "build\bdist.win-amd64\egg\PyPDF2\pdf.py", line 1065, in __init__
File "build\bdist.win-amd64\egg\PyPDF2\pdf.py", line 1660, in read
IOError: [Errno 22] Invalid argument
Below is the relevant code. I'm not sure how to correct this issue because I'm not really sure what the issue is. Any guidance is appreciated.
for ID in FileDict:
if ID in EmailDict :
path = "C:\\Apps\\CorVu\\DATA\\Reports\\AlliD\\Monthly Commission Reports\\Output\\pdcom1\\"
#print os.listdir(path)
file = os.path.join(path + FileDict[ID])
with open(file, 'rb') as input:
print type(input)
inputStream = PyPDF2.PdfFileReader(input)
output = PyPDF2.PdfFileWriter()
output = inputStream.encrypt(EmailDict[ID][1])
with open(file, 'wb') as outputStream:
output.write(outputStream)
else : continue
I think your problem might be caused by the fact that you use the same filename to both open and write to the file, opening it twice:
with open(file, 'rb') as input :
with open(file, 'wb') as outputStream :
The w mode will truncate the file, thus the second line truncates the input.
I'm not sure what you're intention is, because you can't really try to read from the (beginning) of the file, and at the same time overwrite it. Even if you try to write to the end of the file, you'll have to position the file pointer somewhere.
So create an extra output file that has a different name; you can always rename that output file to your input file after both files are closed, thus overwriting your input file.
Or you could first read the complete file into memory, then write to it:
with open(file, 'rb') as input:
inputStream = PyPDF2.PdfFileReader(input)
output = PyPDF2.PdfFileWriter()
output = input.encrypt(EmailDict[ID][1])
with open(file, 'wb') as outputStream:
output.write(outputStream)
Notes:
you assign inputStream, but never use it
you assign PdfFileWriter() to output, and then assign something else to output in the next line. Hence, you never used the result from the first output = line.
Please check carefully what you're doing, because it feels there are numerous other problems with your code.
Alternatively, here are some other tips that may help:
The documentation suggests that you can also use the filename as first argument to PdfFileReader:
stream – A File object or an object that supports the standard read
and seek methods similar to a File object. Could also be a string
representing a path to a PDF file.
So try:
inputStream = PyPDF2.PdfFileReader(file)
You can also try to set the strict argument to False:
strict (bool) – Determines whether user should be warned of all
problems and also causes some correctable problems to be fatal.
Defaults to True.
For example:
inputStream = PyPDF2.PdfFileReader(file, strict=False)
Using open(file, 'rb') was causing the issue becuase PdfFileReader() does that automagically. I just removed the with statement and that corrected the problem.
with open(file, 'rb') as input:
inputStream = PyPDF2.PdfFileReader(input)
This error raised up because of PDF file is empty.
My PDF file was empty that's why my error was raised up. So First of all i fill my PDF file with some data and Then start reeading it using PyPDF2.PdfFileReader,
And it solved my Problem!!!
Late but, you may be opening an invalid PDF file or an empty file that's named x.pdf and you think it's a PDF file

Python coding error: "file doesn't exist" [duplicate]

This question already has answers here:
open() gives FileNotFoundError / IOError: '[Errno 2] No such file or directory'
(8 answers)
Closed 7 years ago.
I have a text file named hsp.txt in C:\Python27\Lib\site-packages\visual\examples and used the following code.
def file():
file = open('hsp.txt', 'r')
col = []
data = file.readlines()
for i in range(1,len(data)-1):
col.append(int(float(data[i].split(',')[5])))
return col
def hist(col):
handspan = []
for i in range(11):
handspan.append(0)
for i in (col):
handspan[i] += 1
return handspan
col = file()
handspan = hist(col)
print(col)
print(handspan)
But when I run it it says that that the file doesn't exist.
Traceback (most recent call last):
File "Untitled", line 17
col = file()
File "Untitled", line 2, in file
file = open('hsp.txt', 'r')
IOError: [Errno 2] No such file or directory: 'hsp.txt'
How do I fix this?
Also how do I output the mean and variance?
Have you thought where your path leads to? You need to supply the complete path to the file.
opened_file = open("C:/Python27/Lib/site-packages/visual/examples/hsp.txt")
A couple other things:
Don't use file as a variable name. The system already uses that name.
Use a with statement. It's considered better practice.
with open("C:/Python27/Lib/site-packages/visual/examples/hsp.txt"):
# do something
When the with block ends, the file is automatically closed. In your code, the file is left open until the file function is closed (and hence saved) with the .close() method.
When your specifying just the following line
file = open('hsp.txt', 'r')
It is trying to use your current directory, that is where ever you launched python from. So if you, from a command prompt were at C:\temp and executed python test.py it woud look for your hsp.txt in C:\temp\hsp.txt. You should specify the full path when your not trying to load files from your current directory.
file = open(r'C:\Python27\Lib\site-packages\visual\examples\hsp.txt')

Using python to read text files and answer questions

I have this file animallog1.txt which contains information that i would like to use to answer questions using python. How would i import the file to python, which would latter be used
I tried
with open('animallog1.txt', 'r') as myfile
but this is not working and just outputs no such file or directory even though i am pretty sure it exists
animal_names, dates, locations = [], [], []
with open('animallog1.txt', 'r') as myfile:
for line in myfile:
animal_name, date, location = line.strip().split(':')
animal_names.append(animal_name)
dates.append(date)
locations.append(location)
print(animal_names)
print(dates)
print(locations)
so this is the code that i have. animallog1.txt is the name of the file that i want to use.
However my output is
Traceback (most recent call last):
File "None", line 3, in <module>
builtins.FileNotFoundError: [Errno 2] No such file or directory: 'animallog1.txt'
how can i fix this?
Make sure you path is corret or try this:
file = open("sample.txt")
sample.txt is present in the current path, in my ubuntu it works.
I would take a look at this. So modifying your code could be like:
f = open('animal data.txt', 'r+');
f.readline(); //Do this until you've read your questions
f.write('Answer to the questions')

How can I edit a plain text file in Python?

I've been trying to create a python script that edits a file, but if the file is not already there, it has an error like this:
Traceback (most recent call last):
File "openorcreatfile.py", line 56, in <module>
fileHandle = (pathToFile, 'w')
IOError: [Errno 2] No such file or directory: '/home/me/The_File.txt'
It works fine if the file exists. I've also tried this:
fileHandle = (pathToFile, 'w+')
But it comes up with the same error. Do I need to explicitly check if the file is there? If so, how do I create the file?
EDIT: Sorry, I realized the folder was missing. I'm an idiot.
The error says "No such file or directory."
Since you're trying to create a file, that must not be what's missing. So you need to create the /home/me/ directory.
See os.makedirs.
fo = open("myfile.txt", "wb")
fo.write('blah')
fo.close()
That's it, this will do the job.
myfile = open('test.txt','w')
myfile.write("This is my first text file written in python\n")
myfile.close()
To check if the file is there you can do:
import os.path
os.path.isfile(pathToFile)
so you can handle it, only if it exists:
if os.path.isfile(pathToFile):
fileHandle = (pathToFile, 'w')
else:
pass #or other thing
There are several ways to create a file in python, but if you want to create a text file, take a look at numpy.savetxt, which I think is one of the easiest and most effective ways
with open("filename.txt", "w") as f:
f.write("test")

Categories

Resources