Import and Export using OS in Python - python

I want to import all data using path but I keep getting error. And how can I get an output in a separate file?
Input File:
import os,json
path= "./Responses"
for file in os.listdir(path):
with open (file) as json_file:
data=json.load(json_file)
Error Message:
FileNotFoundError: [Errno 2] No such file or directory: 'data_1.json'
And can I separate the new data by using 'Out'?
Output File:
for file in os.listdir(path):
with open(json_data, 'w') as outfile:
json.dump('Out'+ data, outfile, indent=4)

The reason why you got error because python script cannot find the relative path for the file founded in "with open (file) as json_file:"
To fix that you can change that to:
with open (path +'/'+ file) as json_file:

Related

Read a file within an archived archive (without extracting)

What I am trying to do is to read a file located in an archived archive as shown below:
I want to access a "document.txt" file
Code 1:
import zipfile
with zipfile.ZipFile("archive.zip", mode="r") as archive:
with zipfile.ZipFile("archive2.zip", mode="r") as archive2:
text = archive2.read("document.txt")
print(text) #FileNotFountError: [Errno 2] No such file or directory: 'archive2.zip'
Code 2:
import zipfile
with zipfile.ZipFile("archive.zip/archive2.zip", mode="r") as archive:
text = archive.read("document.txt")
print(text) #FileNotFountError: [Errno 2] No such file or directory: 'archive.zip/archive2.zip'
None of the above works. How can I read a "document.txt" file that is located in an "archive2.zip", which in turn is located in an "archive.zip" file without extracting anything? Thank you very much.
archive.zip file for your reference
You need to open first then read it.
Ex:-
import zipfile
with zipfile.ZipFile("archive.zip/archive2.zip", mode="r") as archive:
text = archive.open("document.txt").read().decode()
print(text)
You first need to open archive.zip, then read the raw archive2.zip file and finally read the document within that zip file.
import zipfile
with zipfile.ZipFile(r"archive.zip", "r") as archive:
with zipfile.ZipFile(archive.open(r"archive/archive2.zip", "r")) as archive2:
doc = archive2.open("archive2/document.txt")
content = doc.readlines()
print(content)

How to create a directory?

I tried using open but it gives an error that the folder doesn't exist, which makes no sense since this is a command to create a folder, not read one. I saw Automatically creating directories with file output, but there is an error saying this is a Errno 30: Read only system: "/folder". Does anyone know how to avoid Error 30?
My code so far:
import os
filename = "/folder/y.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
f.write("FOOBAR")
I figured i just shouldn't put the slash behind the "folder"filename = "folder/y.txt" os.makedirs(os.path.dirname(filename), exist_ok=True) with open(filename, "w") as f: f.write("FOOBAR")

Save .csv file in the same directory as .py file

I am tring to save my .csv file which is a result of some queries in the same location as the .py file.
import os
with open(os.path.dirname(os.path.abspath(__file__))+'MyCSVFile.csv','wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(myList)
I always seem to get my csv file one directory before. When I print os.path.dirname(os.path.abspath(__file__)) it gives me the proper path but the output MyCSVFile is saved one above. What is the problem here?
You have to use os.path.join to save the csv file in the same directory
import os
dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'MyCSVFile.csv')
with open(csvfilename, 'wb') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(myList)
This should work as excepted
Remove the call to os.path.dirname since you are already calling os.path.abspath. Calling dirname returns the directory component thus you are getting the directory up in the hierarchy. BTW: use os.path.join to join parts of a directory.

OS listdir not reading certain files

I'm trying to access a folder and read the text files in it. Eventually I'm going to build them into a basic dictionary to dump into JSON but something's going on with the files. I'm getting an error message:
FileNotFoundError: [Errno 2] No such file or directory: ___
The thing is, this code IS working on my test files ... so maybe it's somehow a file issue?
import json
import os
for file in os.listdir("filepath"):
with open ('%s.json' % file, 'w') as fp:
file = f.read()
f = open(file, 'r')
print (f)
These are the text files not getting 'found/read':
https://drive.google.com/open?id=0B4zJC6biI6jERDFHSzZvUUJaRE0
Has anyone else run into this problem / found a solution that might work?

Python 2.5.2: trying to open files recursively

The script below should open all the files inside the folder 'pruebaba' recursively but I get this error:
Traceback (most recent call last):
File
"/home/tirengarfio/Desktop/prueba.py",
line 8, in
f = open(file,'r') IOError: [Errno 21] Is a directory
This is the hierarchy:
pruebaba
folder1
folder11
test1.php
folder12
test1.php
test2.php
folder2
test1.php
The script:
import re,fileinput,os
path="/home/tirengarfio/Desktop/pruebaba"
os.chdir(path)
for file in os.listdir("."):
f = open(file,'r')
data = f.read()
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
data)
f.close()
f = open(file, 'w')
f.write(data)
f.close()
Any idea?
Use os.walk. It recursively walks into directory and subdirectories, and already gives you separate variables for files and directories.
import re
import os
from __future__ import with_statement
PATH = "/home/tirengarfio/Desktop/pruebaba"
for path, dirs, files in os.walk(PATH):
for filename in files:
fullpath = os.path.join(path, filename)
with open(fullpath, 'r') as f:
data = re.sub(r'(\s*function\s+.*\s*{\s*)',
r'\1echo "The function starts here."',
f.read())
with open(fullpath, 'w') as f:
f.write(data)
You're trying to open everything you see. One thing you tried to open was a directory; you need to check if an entry is a file or is a directory, and make a decision from there. (Was the error IOError: [Errno 21] Is a directory not descriptive enough?)
If it is a directory, then you'll want to make a recursive call to your function to walk over the files in that directory as well.
Alternatively, you might be interested in the os.walk function to take care of the recursive-ness for you.
os.listdir lists both files and directories. You should check if what you're trying to open really is a file with os.path.isfile

Categories