Python: Creating and writing to a file error - python

I am having trouble creating and writing to a text file in Python. I am running Python 3.5.1 and have the following code to try and create and write to a file:
from os import *
custom_path = "MyDirectory/"
if not path.exists(custom_path)
mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, "w")
text_file.write("my text")
But I get a TypeError saying an integer is required (got type str) at the line text_file = open(text_path, "w").
I don't know what I'm doing wrong as my code is just about identical to that of several tutorial sites showing how to create and write to files.
Also, does the above code create the text file if it doesn't exist, and if not how do I create it?

Please don't import everything from os module:
from os import path, mkdir
custom_path = "MyDirectory/"
if not path.exists(custom_path):
mkdir(custom_path)
text_path = custom_path + "MyTextFile.txt"
text_file = open(text_path, 'w')
text_file.write("my text")
Because there also a "open" method in os module which will overwrite the native file "open" method.

Related

Issue writting to file with pyinstaller

So an update, I found my compile issue was that I needed to change my notebook to a py file and choosing save as doesn't do that. So I had to run a different script turn my notebook to a py file. And part of my exe issue was I was using the fopen command that apparently isn't useable when compiled into a exe. So I redid the code to what is above. But now I get a write error when trying to run the script. I can not find anything on write functions with os is there somewhere else I should look?
Original code:
import requests
import json
import pandas as pd
import csv
from pathlib import Path
response = requests.get('url', headers={'CERT': 'cert'}, stream=True).json()
json2 = json.dumps(response)
f = open('data.json', 'r+')
f.write(json2)
f.close()
Path altered code:
import requests
import json
import pandas as pd
import csv
from pathlib import Path
response = requests.get('url', headers={'CERT': 'cert'}, stream=True).json()
json2 = json.dumps(response)
filename = 'data.json'
if '_MEIPASS2' in os.environ:
filename = os.path.join(os.environ['_MEIPASS2'], filename)
fd = open(filename, 'r+')
fd.write(json2)
fd.close()
The changes to the code allowed me to get past the fopen issue but created a write issue. Any ideas?
If you want to write to a file, you have to open it as writable.
fd = open(filename, 'wb')
Although I don't know why you're opening it in binary if you're writing text.

Python3 - Cannot import local module due to FileNotFoundError

Within my code I am attempting to import modules written by myself. Said modules interact with files on the system, either encrypting, decrypting or removing them altogether. When trying to import these modules I receive the below:
FileNotFoundError: [Errno 2] No such file or directory: <Directory>
Oddly this error seems to appear before anything local within the file runs (calls are at the end), making me believe python is parsing the files during the import phase and not find the files (apologies but I am novice when it comes to importing self created stuff)
Below is one of the methods I am importing (also the one flagging the error)
import urllib.request, re, os
def getKey(url, path):
urllib.request.urlretrieve(url, 'C:\\code\\'+path)
def readFiles(keyFile, targetFile, outfile):
infile = keyFile # read in the input file name
infd = open('C:\\code\\'+infile,"r") # open the file and create the file descriptor infd
key = infd.read( )
key = key.strip('\n')
#print('key= '+key)
infile = targetFile
infd = open('C:\\code\\'+infile, "r")
ptext = infd.read( ).strip('\n')
infd.close
xor(outfile, ptext, key)
def xor(outfile, ptext, key):
outfd = open('C:\\code\\'+outfile, "w")
pLength = len(ptext)
#get the length of the plaintext and cut the key into the same size
keyChunks = [key[i:i+pLength] for i in range(0, len(key), pLength)]
i = 0
while i < len(keyChunks):
a = int(ptext)
b = int(keyChunks[i])
out = a ^ b
i=i+1
outfd = open('C:\\code\\'+outfile, "w")
outfd.write(str(out))
outfd.close
def cleanup(targetFile):
os.remove(targetFile)
def enc():
outfile = 'affk.xor'
getKey('http://192.168.56.10/sym.key', 'sym.key')
readFiles('sym.key', 'affk.txt', outfile)
cleanup('C:/code/affk.txt')
def dec():
outfile = 'affk.txt'
getKey('http://192.168.56.10/sym.key', 'sym.key')
readFiles('sym.key', 'affk.xor', outfile)
cleanup('C:/code/affk.xor')
cleanup('C:/code/sym.key')
enc()
#dec()
Below is a snippet of my main file with the imports and calling function
import os, math, affine, re, urllib.request, ctypes
from xor import enc
from rsa1 import run
---Additional Code here---
def main():
# Call function to search for the files we want to encrypt
search()
# Call function to read the target files. Main ciphers are daisy chained off reader function
reader(targets)
# Call function to XOR Affine cipher key
xor.enc()
# Call function to encrypt key used for above XOR using RSA
rsa1.run()
Any assistance with this problem would be greatly appreciated! Apologies if this is an extremely dumb question!

How to Change First Line of File in Python?

Why does Python-2.7 on Windows truncate a file? The problem is well known with shutil.copyfile but I don't understand how to avoid it when I'm changing the first line. File size is unknown and could be huge.
Reference below but I'd prefer better exception handling with something like the following code:
import os
import sys
import shutil
with open(sys.argv[1], 'r+') as src:
line = src.readline()
with open(sys.argv[1], 'r+') as dst:
dst.write = sys.argv[1]+'\n'
shutil.copyfileobj(src, dst)
Reference: change first line of a file in python
You need to create the new version of the file as a NamedTemporaryFile. After you finish constructing it, you then rename it on top of the old file.
Code:
def insert_line_front(insert_filename, to_insert):
with open(insert_filename) as src, tempfile.NamedTemporaryFile(
'w', dir=os.path.dirname(insert_filename), delete=False) as dst:
# Discard first line
src.readline()
# Save the new first line
dst.write(to_insert + '\n')
# Copy the rest of the file
shutil.copyfileobj(src, dst)
# remove old version
os.unlink(insert_filename)
# rename new version
os.rename(dst.name, insert_filename)
return()
Test Code:
import os
import shutil
import sys
import tempfile
# For noob - Function code goes here
filename = os.path.abspath(sys.argv[1])
insert_line_front(filename, filename)
Before:
/testcode/file1
"-3.588920831680E-02","1.601887196302E-01","1.302309112549E+02"
"3.739478886127E-01","1.782759875059E-01","6.490543365479E+01"
"3.298096954823E-01","6.939357519150E-02","2.112392578125E+02"
"-2.319437451661E-02","1.149862855673E-01","2.712340698242E+0
After:
/testcode/file2
"-3.588920831680E-02","1.601887196302E-01","1.302309112549E+02"
"3.739478886127E-01","1.782759875059E-01","6.490543365479E+01"
"3.298096954823E-01","6.939357519150E-02","2.112392578125E+02"
"-2.319437451661E-02","1.149862855673E-01","2.712340698242E+0

Python reportlab save with canvas to specified location

I am wondering how I can make my script save to the Desktop. Here's my code:
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Image
import csv
import os
data_file = "hata.csv"
def import_data(data_file):
inv_data = csv.reader(open(data_file, "r"))
for row in inv_data:
var1 = row[0]
# do more stuff
pdf_file = os.path.abspath("~/Desktop/%s.pdf" % var1)
generate_pdf(variable, pdf_file)
def generate_pdf(variable, file_name):
c = canvas.Canvas(file_name, pagesize=letter)
# do some stuff with my variables
c.setFont("Helvetica", 40, leading=None)
c.drawString(150, 2300, var1)
c.showPage()
c.save()
import_data(data_file)
So this works perfectly, and it saves/creates the PDF I want -- but in the directory of the script. I would instead like to save it to, say, the Desktop.
When I researched and found os.path.abspath, I thought I solved it; but I receive the following error
File "/usr/local/lib/python3.4/site-packages/reportlab/pdfbase/pdfdoc.py", line 218, in SaveToFile
f = open(filename, "wb")
FileNotFoundError: [Errno 2] No such file or directory: '/Users/TARDIS/Desktop/tests/~/Desktop/00001.pdf'
which tells me that it's trying to save starting from my script's home folder. How do I get it to see outside of that?
After much trial and error using different methods that all had drawbacks, I came up with a solution and figured I'd post it here for posterity. I'm rather new to programming so apologies if this is obvious to the more experienced.
First, I give my pdf file a name:
pdf_name = number + ".pdf"
Then, I find the path to the Desktop for current user (given that I don't know what the user name will be, which was the original root of the problem) and create a path to it so that the pdf can be to be saved there.
save_name = os.path.join(os.path.expanduser("~"), "Desktop/", pdf_name)
Finally, that's passed in to my pdf generation function:
...
save_name = ....
generate_pdf(variable, save_name)
def generate_pdf(variable, save_name):
c = canvas.Canvas(save_name, pagesize=letter)
....
And that's it.

PDF merging in Python 3

Is there a working PDF manipulation module for Python 3? I've tried Pypdf, but it glitches out when I try to install with PIP. I'd like to merge PDF files. If I use Pypdf2, I get the following message using this code:
from pypdf2 import merger, PdfFileReader
with open('test1.pdf', 'rb') as f:
with open('test2.pdf', 'rb') as f2:
merger = PdfFileMerger()
merger.merge(position=0, fileobj=f2)
merger.merge(position=0, fileobj=f)
merger.write(open("test_out.pdf", 'wb'))
"File "c:\...merger.py", line 97, in merge
elif type(fileobj) == file:
NameError: global name 'file' is not defined"
Line 97 of merger.py is:
elif type(fileobj) == file:
I get similar errors in my own code when using code such as
input1 = PdfFileReader(file("document1.pdf", "rb")) - that's a copy and paste from http://www.blog.pythonlibrary.org/2012/07/11/pypdf2-the-new-fork-of-pypdf/
It seems that is a bug in PyPDF2... file is gone in python3, that's why you get an error here.
A quick fix would be to add this to the imports in merger.py:
from io import FileIO as file

Categories