I have two files in a directory. One is a .CSV file and other is a Python script. Python code looks like this:
from pyx import *
import csv
import re
import sys
def write():
name = raw_input('Enter the name of .dat file: ') + '.dat'
file = open(name, "w")
for i in range(0, len(x_lista)-1):
file.write(x_lista[i])
file.write(" ")
file.write(y_lista[i])
file.write("\n")
file.close()
def read_CSV(x_lista, y_lista):
currency = raw_input('Enter the name of input .CSV file: ') + '.CSV'
#print currency
with open(currency, 'rb') as f:
reader = CSV.reader(f)
lista = list(reader)
print lista
if(currency == 'Frank' or 'USD'):
factor = 4
else:
factor = 3
for i in range (3, len(lista)-factor):
temp = (re.split(r'[";"]', (';'.join(lista[i]))))
temp1 = temp[0]
x_lista.append(temp1)
temp1 = temp[1]
y_lista.append(temp1)
print x_lista, y_lista
x_lista = []
y_lista = []
read_CSV(x_lista, y_lista)
write()
It takes what's in .CSV and by splitting/joining lists it produces a .DAT file consisting of two columns of data. Well... it does on Windows. However, when I try to compile it on Ubuntu I get this:
Enter the name of input .CSV file: Euro
Traceback (most recent call last):
File "nwb.py", line 46, in <module>
read_CSV(x_lista, y_lista)
File "nwb.py", line 22, in read_CSV
with open(currency, 'rb') as f:
IOError: [Errno 2] No such file or directory: 'Euro.CSV'
What would be the solution?
In Unix system file names are case sensitive.
For example: Euro.CSV and Euro.csv are different file names. Maybe the error is shown because of that
Related
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")
Problem:
When I try to import data from a text file to python it says no such file or directory. I really am a beginner so I would really appreciate it if someone could provide me with better code for the same purpose.
What I want to do: take input from the user in a text file and replace the letter 'a' with 'b'. The program should then give the output in a text file to the user.
My code:
import os
texttofind = 'a'
texttoreplace = 'b'
sourcepath = os.listdir ('InputFiles')
for file in sourcepath:
inputfile = 'InputFiles' + file
with open(inputfile, 'r') as inputfile:
filedata = inputfile.read()
freq = 0
freq = filedata.count(texttofind)
destinationpath = 'OutputFIle' + file
filedata = filedata.replace(texttofind , texttoreplace)
with open(destinationpath,'w') as file:
file.write(filedata)
print ('the meassage has been encrypted.')
First of all I wouldn't use only "InputFiles" in os.listdir(), but a Relative or Absolute Path.
Then when you get all the subdirs, you get only the names:
eg: "a", "b", "c", ...
This means that whent you concatenate sourcepath to file you get something like InputFilesa so not the file you were looking for.
It should look like: InputFiles/a
Taking into consideration what I told you, now your code should look like:
import os
texttofind = 'a'
texttoreplace = 'b'
my_dir = "./InputFiles"
sourcepath = os.listdir(my_dir)
for file in sourcepath:
inputfile = my_dir + f"/{file}"
with open(inputfile, 'r') as inputfile:
filedata = inputfile.read()
freq = 0
freq = filedata.count(texttofind)
destinationpath = 'OutputFile' + f"/{file}"
filedata = filedata.replace(texttofind, texttoreplace)
with open(destinationpath,'w') as file:
file.write(filedata)
print ('the meassage has been encrypted.')
I have this text file, that contains user information. I want to parse the data, so I only have the username, and then I want to create a csv file with that parsed data.
This is the text file, my script is reading from.
blah.com\user1:dajlfnadjhlasdjasnasjlfn:test1
blah.com\user2:dajlfnadjhlasdjasnasjlfn:test2
blah.com\user3:dajlfnadjhlasdjasnasjlfn:test3
blah.com\user4:dajlfnadjhlasdjasnasjlfn:test4
blah.com\user5:dajlfnadjhlasdjasnasjlfn:test5
blah.com\user6:dajlfnadjhlasdjasnasjlfn:test6
Here is my script
import time, os, os.path, sys, string, datetime, time, shutil, csv
#Locate the file
globalpath = 'C:\\users\\userinfo\\'
todaysdatefull = datetime.datetime.now()
todaysdate = todaysdatefull.strftime("%Y-%m-%d")
datapath = globalpath + 'data\\' + todaysdate + "\\"
logfile = datapath + 'userinfo.txt'
potfile = datapath + 'parsed.csv'
infile = logfile
outfile = potfile
lines = []
# Open the file, find the username and parses it
with open(infile, 'r') as f:
for line in f:
usernamestart = line.find('\\')
usernameend = line.find(':')
username = line[usernamestart+1:usernameend]
lines.append(username)
print(username)
# Outputs the data as a csv file
with open(outfile, 'w') as csv:
writer = csv.writer(csv)
for i in range(len(lines)):
writer.writerow(('Username', 'Date'))
writer.writerow(lines[i])
Result:
Traceback (most recent call last):
File "C:\Automation\autocrack\highrisk_parser.py", line 33, in <module>
writer = csv.writer(csv)
AttributeError: 'file' object has no attribute 'writer'
It is coming from this line
with open(outfile, 'w') as csv:, your are overwriting the csv import. You should rename the file where you write like this
with open(outfile, 'w') as csv_to_write:
writer = csv.writer(csv_to_write)
# Write the header once.
writer.writerow(tuple(['Username', 'Date']))
for one_line in lines:
# you have to give the function a tuple, if not, the writerow iterates on each element of the string for writing it in a new line.
writer.writerow(tuple([one_line, '']))
Your first part of code finding the username can be done as following:
with open(infile, 'r') as f:
lines = [line.split('\\')[-1].split(':')[0] for line in f]
I'm trying to make a number of text files within a loop and naming them with respect to their number like data1.txt, data2.txt and so forth.
I = 0
while I < 4:
file_name = "data" + str(I) + ".txt"
with open(file_name, 'w') as L:
L.write('stuffIWannaWrite')
I += 1
But when I run this code, it says that the file cannot be found:
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'data0.txt'
any help?
EDIT
i'm working on a virtualenv for a scraping project..
the problem only arises when the file name is in iteration like,
file_name = "data" + str(I) + ".txt" in which I is being iterated ,
the code works fine on a simple file name like..
file = open("try.txt", 'w')
file.write(main_stuff)
i.e text file is being created..
I guess this code will do the trick.
import numpy as np
list1=list(np.arange(10))
for num in list1:
with open('data%d.txt'%num,'a') as in_file:
in_file.write("stuff you want to write")
I'm using the following approach.
First name down the list of items in .zip file using namelist() and than use a specific item from the namelist and open it.
It's not working for me.
import zipfile
import gzip
nameofFile = raw_input("Enter File Name:")
def TEST():
zf = zipfile.ZipFile(nameofFile, 'r')
x = zf.namelist( )
y = x[-4]
print y
with gzip.open(y, 'rb') as f:
for line in f:
if "Apple" in line:
print "Fruit"
break
TEST()
Following is the result of print y: Log_File/Result.gz
Please help, thanks in advance.
With
with gzip.open(y, 'rb') as f:
you are opening a file outside the Zip. You need to do something like
gzip.GzipFile(zf.open(y))