OSError: [Errno 22] Invalid argument while opening a file - python

I am currently working on an application which translates a input file row by row and writes the translated row into a output file but I get the following error when running my script: OSError: [Errno 22] Invalid argument: '{parent_id:opynw1, body: my text'
Full error message:
Traceback (most recent call last):
File "test.py", line 12, in <module>
column1= GoogleTranslator(source='german', target='english').translate_file(row)
File "C:\Users\supre\anaconda3\envs\test\lib\site-packages\deep_translator\google_trans.py", line 136, in translate_file
raise e
File "C:\Users\supre\anaconda3\envs\test\lib\site-packages\deep_translator\google_trans.py", line 132, in translate_file
with open(path) as f:
OSError: [Errno 22] Invalid argument: '{parent_id:opynw1, body: my text'
Content of my input text file:
{parent_id:opynw1, body: my text}
{parent_id:h68dhu3, body: my text}
{parent_id:opynw1, body: my text}
My code:
from deep_translator import GoogleTranslator
output_file = open('./test.txt', 'w',encoding='utf-8')
reader = open('./data.txt', 'r', encoding='utf-8')
for row in reader:
column1= GoogleTranslator(source='english', target='german').translate_file(row)
output_text = str(column1)
output_file.write(output_text + '\n')
output_file.close()
Is there something wrong with my script? If so I would be glad if someone could tell me what I've made wrong and help me to solve this problem:)
Thank's for every help and suggestion in advance:)

Use translate() rather than translate_file(), since the line is not a filename.
You also need to use ast.literal_eval() to parse it into a dictionary.
from deep_translator import GoogleTranslator
import ast
with open('./test.txt', 'w',encoding='utf-8') as output_file, open('./data.txt', 'r', encoding='utf-8') as reader:
for row in reader:
d = ast.literal_eval(row)
column1= GoogleTranslator(source='english', target='german').translate(d['body'])
output_text = str(column1)
output_file.write(output_text + '\n')

Related

I am unable to create multiple files with this code, what is wrong?

So I'm trying to write a program that takes names from a list and adds it to a letter. A text file is created for each name for the letter however the code seems to stop working at that point.
letter = []
names = []
file = open("Input/Letters/starting_letter.txt", "r")
letter = file.readlines()
file.close()
name1 = open("Input/Names/invited_names.txt", "r")
names = name1.readlines()
name1.close()
for name in names:
create_letter = open(f"{name}.txt", "w")
for line in letter:
line = line.replace("[name],", f"{name},")
create_letter.write(line)
create_letter.close()
I get the error message
Traceback (most recent call last):
File "C:\Users\Default User\PycharmProjects\Mail Merge Project Start\main.py", line 10, in <module>
create_letter = open(f"{name}.txt", "w")
OSError: [Errno 22] Invalid argument: 'Aang\n.txt'
Is there a problem with the way I am creating the files?
You can't have newlines in your file name. It is invalid in your OS/filesystem.
Remove them with:
open(f"{name.strip()}.txt", "w")
Or:
open(f"{name.replace('\n', '')}.txt", "w")

Cannot Export API call data to CSV

I am trying to export the json received from an API call to csv using the code below but getting the error messages:
import requests
import csv
import json
r='http://openapi.seoul.go.kr:8088/504949776872656935396c46496663/json/airPolutionMeasuring1Hour/1/50/'
response=requests.get(r)
output = response.text
jsonresponse=json.loads(output)
with open ('data_02.csv', 'w', newline ='') as csvfile:
fieldnames=['DATA_DT', 'LOC_CODE', 'ITEM_CODE', 'DATA_VALUE', 'DATA_STATE', 'DATA_NOVER', 'DATA_ROVER', "REGIST_DT"]
writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
for row in jsonresponse:
writer.writerow(row)
#print(output)
The error message:
Traceback (most recent call last): File
"/Users/xxx/PycharmProjects/api_request/export_csv_Test02.py", line
16, in
writer.writerow(row) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/csv.py",
line 154, in writerow
return self.writer.writerow(self._dict_to_list(rowdict)) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/csv.py",
line 147, in _dict_to_list
wrong_fields = rowdict.keys() - self.fieldnames AttributeError: 'str' object has no attribute 'keys'
Instead of
for row in jsonresponse:
writer.writerow(row)
Use:
writer.writerows(jsonresponse)
import requests
import csv
import json
r='http://openapi.seoul.go.kr:8088/504949776872656935396c46496663/json/airPolutionMeasuring1Hour/1/50/'
response=requests.get(r)
output = response.text
jsonresponse=json.loads(output)
with open ('data_02.csv', 'w', newline ='') as csvfile:
fieldnames=['DATA_DT', 'LOC_CODE', 'ITEM_CODE', 'DATA_VALUE', 'DATA_STATE', 'DATA_NOVER', 'DATA_ROVER', "REGIST_DT"]
writer=csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(jsonresponse['airPolutionMeasuring1Hour']['row'])
# print(output)

Python to "find/replace" a string in a .csv file, getting a tracekback name error

Trying to get python to do a "find/replace" for my "test.csv" CSV file, but I am getting the following error when I run the code below:
Traceback (most recent call last):
File "/home/l/gDrive/AudioBookReviews/AmazonBookScrapper/cleanup.py", line 4, in <module>
with open(test.csv, 'r') as f:
NameError: name 'test' is not defined
The Python3 I am running is:
import re
with open(test.csv, 'r') as f:
csv_file = f.read()
find_str = 'audiocassetteprice='
replace_str = ' '
new_csv_str = re.sub(find_str, replace_str, csv_file)
new_csv_path = './NewCSV.csv'
with open(new_csv_path, 'w') as f:
f.write(new_csv_str)

Why do I receive an error stating coercing to unicode in Python?

I am trying to write a code that will fetch an api from my csv as input:
from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults, GetUpdatedPropertyDetails
def get_zillowinfo(address,zipcode):
zillow_data = ZillowWrapper('X1-ZWz17seirkzuh7_93aho')
deep_search_response = zillow_data.get_deep_search_results(address,zipcode)
result1 = GetDeepSearchResults(deep_search_response) #get zillowid from address
updated_property_details_response = zillow_data.get_updated_property_details(result1.zillow_id)
result2 = GetUpdatedPropertyDetails(updated_property_details_response) # get detail property info
result = result2.home_info
return result
print get_zillowinfo('73 main blvd','01545')
#2
import csv
with open(r'C:\Users\bca\Desktop\Pricing Study-Zillow\sample4.csv', 'r') as csvfile:
spamreader = csv.reader(csvfile,delimiter=',')
next(spamreader)
for row in spamreader:
print row
#3
import csv
with open(r'C:\Users\bca\Desktop\Pricing Study-Zillow\sample4.csv', 'r') as csvfile:
spamreader = csv.reader(csvfile,delimiter=',')
next(spamreader)
for row in spamreader:
print get_zillowinfo(row[0],row[1])
When i do step #3, I get an error:
Traceback (most recent call last):
File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 2895, in run_code
self.showtraceback()
File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\IPython\core\interactiveshell.py", line 1828, in showtraceback
self._showtraceback(etype, value, stb)
File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\ipykernel\zmqshell.py", line 547, in _showtraceback
u'evalue' : py3compat.safe_unicode(evalue),
File "C:\Users\bca\AppData\Local\Continuum\anaconda2\lib\site-packages\ipython_genutils\py3compat.py", line 65, in safe_unicode
return unicode_type(e)
TypeError: coercing to Unicode: need string or buffer, dict found
Why does this happen? is it because my characters are not strings? how do I change it to string in that case for all my data?
This is a repex of my dataset:
What do I need to change in my code to avoid that type error?

IOError: [Errno 2] No such file or directory error is presented for the ouptup file

I'm making a Python code to manipulate text files. The code will receive from the command line input file and output file names and a flag -sort, -reverse etc according to manipulation to apply on the input file and finally write the data to output file. I need to do all this job inside a class so the code will be inheritable. So far I have a code like this:
import argparse
import random
class Xiv(object):
def __init__(self):
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-s", "-sort", action="store_true")
group.add_argument("-r", "-reverse", action="store_true")
group.add_argument("-sh", "-shuffle", action="store_true")
parser.add_argument("inputfile", type = file, help="Input file name")
parser.add_argument("outputfile", type = file, help="Output file name")
args = parser.parse_args()
source =args.inputfile
dist = args.outputfile
def sort(self):
f = open(source, "r")
list1 = [line for line in f if line.strip()]
f.close()
list.sort()
with open(dist, 'wb') as fl:
for item in list:
fl.write("%s" % item)
def reverse(self, source, dist):
f = open(source, "r")
list2 = [line for line in f if line.strip()]
f.close()
list2.reverse()
with open(dist, 'wb') as f2:
for item in list2:
f2.write("%s" % item)
def shuffle(self, source, dist):
f = open(source, "r")
list3 = [line for line in f if line.strip()]
f.close()
random.shuffle(list3)
with open(dist, 'wb') as f3:
for item in list3:
f3.write("%s" % item)
x = Xiv();
Now when I run it as
python xiv.py -s text.txt out.txt
it presents the following error
IOError: [Errno 2] No such file or directory 'out.txt'
But 'out.txt' is going to be the output file, I suggest the code to create it in case the file is not already existing. And it worked before I put this code inside the class....
In Python 2, when I call file on a nonexistent file I get this error:
In [13]: file('out.txt')
---------------------------------------------------------------------------
IOError Traceback (most recent call last)
<ipython-input-13-d0d554b7d5b3> in <module>()
----> 1 file('out.txt')
IOError: [Errno 2] No such file or directory: 'out.txt'
In Py2, file is equivalent to open. It opens a file, default in r mode, and thus will give this error if the file does not exist.
In argparse, the type=foo means run the function foo using the input string. It does not mean 'interpret the string as an object of this type'.
In your code:
with open(dist, 'wb') as f2:
for item in list2:
f2.write("%s" % item)
That means you expect dist to be a filename, a string. You don't want the parser to open the file first. You are doing that yourself. So don't specify a type parameter.
#tmoreau - Python3 dropped that file function, leaving only open.
The open function opens a file for reading by default. What you want is to open it in write/create mode, which will create it if it doesn't exist and allow you to write to it:
with open(dist, 'w+') as f3:
The second argument specifies the open mode, and it defaults to 'r', meaning read only.
I'm not sure why it worked before you moved it into the class - by all accounts, it should make no difference.
I was getting this error..
jemdoc index
Traceback (most recent call last):
File "/usr/bin/jemdoc", line 1563, in
main()
File "/usr/bin/jemdoc", line 1555, in main
infile = open(inname, 'rUb')
IOError: [Errno 2] No such file or directory: 'index.jemdoc'
then i have changed
infile = open(inname, 'rUb')
to
infile = open(inname, 'w+')
Then the error was solved.

Categories

Resources