currentLine = ''
ipAddresses = ''
def openFiles():
#RETRIEVE wireShark.txt for reading
currentLine = open("wireShark.txt").read().splitlines()
print("File wireShark.txt was opened.")
ipAddresses = open("IPAddress.txt")
print("File IPAddress.txt was opened.")
return currentLine
return ipAddresses
def CheckLine(currentLine):
ipAddresses.write("Source" + "\t\t" + "Destination\n")
for line in currentLine:
obj = line.split(' ')
if 'Source' in obj and 'Destination' in obj:
temp = currentLine.readline.split()
ipAddresses.write(temp[2] + "\t" + temp[3] + "\n")
openFiles()
CheckLine(currentLine)
I keep getting this error:
Traceback (most recent call last):
File "extractIP.py", line 30, in
CheckLine(currentLine)
File "extractIP.py", line 22, in CheckLine
ipAddresses.write("Source" + "\t\t" + "Destination\n")
AttributeError: 'str' object has no attribute 'write'
The problem may be that you are not familiar with the concepts of returning values and variables.
First, when you access currentLine or ipAddresses in the function openFiles, you are accessing a local variable, instead of the global (i.e. shared between all functions.) Therefore, after openFiles(), ipAddresses is still '', causing Python to fail to write to an empty string. If you meant to access the global variable, you should add
global currentLine
global ipAddresses
to both functions. However, global variables are usually not recommended as they can be accessed (and modified) by too many functions. Instead you can do this
def openFiles():
#RETRIEVE wireShark.txt for reading
currentLine = open("wireShark.txt").read().splitlines()
print("File wireShark.txt was opened.")
ipAddresses = open("IPAddress.txt")
print("File IPAddress.txt was opened.")
return currentLine, ipAddresses
currentLine, ipAddresses = openFiles()
Second, you cannot return two values by writing two consecutive return statements. After the first statement, the execution would already be returned, so the second one would never be reached. See above for the fix.
Last, when you open a file for writing, you must explicitly set the file mode w (or w+, etc, see here for all options). So something like this:
ipAddresses = open("IPAddress.txt", "w")
Related
I am attempting to collect only certain type of data from one file. After that the data is to be saved to another file. The function for writing for some reason is not saving to the file. The code is below:
def reading(data):
file = open("model.txt", 'r')
while (True):
line = file.readline().rstrip("\n")
if (len(line) == 0):
break
elif (line.isdigit()):
print("Number '" + line + "' is present. Adding")
file.close()
return None
def writing(data):
file = open("results.txt", 'w')
while(True):
line = somelines
if line == "0":
file.close()
break
else:
file.write(line + '\n')
return None
file = "model.txt"
data = file
somelines = reading(data)
writing(data)
I trying several things, the one above produced a TypeError (unsupported operand). Changing to str(somelines) did solve the error, but still nothing was written. I am rather confused about this. Is it the wrong definition of the "line" in the writing function? Or something else?
See this line in your writing function:
file.write(line + '\n')
where you have
line = somelines
and outside the function you have
somelines = reading(data)
You made your reading function return None. You cannot concat None with any string, hence the error.
Assuming you want one reading function which scans the input file for digits, and one writing file which writes these digits to a file until the digit read is 0, this may help:
def reading(file_name):
with open(file_name, 'r') as file:
while True:
line = file.readline().rstrip("\n")
if len(line) == 0:
break
elif line.isdigit():
print("Number '" + line + "' is present. Adding")
yield line
def writing(results_file, input_file):
file = open(results_file, 'w')
digits = reading(input_file)
for digit in digits:
if digit == "0":
file.close()
return
else:
file.write(digit + '\n')
file.close()
writing("results.txt", "model.txt")
I run this code in the Python IDLE, and it will only return the amount of letters specified instead of the line specified.
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline(1)
else:
race = intro()
When I print the race variable, it comes out as the G (The input name is Grant).
The text file looks like this
Grant
Human
What Am I doing wrong?
race = file.readline(1) returns 1 byte (character) of the line (see here). You want to return the entire line so call race = file.readline().
Are you trying to read a single line, or all the lines? file.readline() will return the first line of the file as a string. If called again, it will return the second line, and so on. You can also load all the lines of the file as a list with file.readlines(), and then get the first or second element by using [0] or [1], so file.readlines()[1] will yield "Human".
if os.path.exists(saveDir + name + '.txt') == True:
print('welcome back ' + name + '.')
file = open(saveDir + name + '.txt')
race = file.readline() # this reads one line at a time
raceType = file.readline() # this will give you the second line (human)
else:
race = intro()
This question already has answers here:
How do I get a result (output) from a function? How can I use the result later?
(4 answers)
Closed 6 months ago.
Trying to simplify lots of repetitive reading and writing in a script of mine, and I can not figure out how to get data out of def readfile.
def writefile(FILE, DATA):
file = open(FILE, "w")
X = str(DATA)
file.write(X)
file.close()
def readfile(FILE):
file = open(FILE, "r")
readvar = file.read()
file.close()
readfile("BAL.txt")
print(readvar)
I would expect the value stored in BAL.txt to come back, but it always says that readvar is not defined. I just defined it in a function that I ran.
Error:
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-6-f80fb5b2da05> in <module>
14
15 readfile("test.txt")
---> 16 print(readvar)
NameError: name 'readvar' is not defined
In Python, variables from inside a function are generally not accessible from the outside (Look up variable scoping).
You can put a return statement at the end of a function to return variables (readvar in this case) (and you almost always should).
Then you can assign the returned argument (readvar) to a new variable (e.g. rv).
You can also give it the same name.
Other Resources:
Python Scopes and Namespaces
Real Python: Defining Your Own Python Function
def writefile(FILE, DATA):
file = open(FILE, "w")
X = str(DATA)
file.write(X)
file.close()
def readfile(FILE):
file = open(FILE, "r")
readvar = file.read()
file.close()
return readvar
rv = readfile("BAL.txt")
print(rv)
You're unable to see the value of readvar because it's only locally defined within the scope of the readfile function, not globally, as you're attempting to use it when calling print(readvar).
If you need a value to persist outside the scope of the function, you must return it to where the function is called, like so:
def readfile(FILE):
file = open(FILE, "r")
file_data = file.read()
file.close()
return file_data
file_data = readfile("my_file.txt")
print(file_data)
I'd also suggest using a with block when performing file operations. It's best practice as to ensure the file handle is correctly closed, even if exceptions occur. This improves the handling of any errors the operation may encounter. For example:
def writefile(FILE, DATA):
data = str(DATA)
with open(FILE, 'w') as write_stream:
write_stream.write(data)
def readfile(FILE):
with open(FILE, 'r') as read_stream:
file_data = read_stream.read()
return file_data
file_data = readfile("my_file.txt")
print(file_data)
If you wanted to access the file line-by-line, we simply include a for loop within the scope of with. For example, printing each line of the file:
def readfile(FILE):
with open(FILE, 'r') as read_stream:
for line in read_stream
print(line)
simple. try this one
def personal_data():
name1 = input("What is you 1st Name?").upper()
name2 = input("What is your last Name?").upper()
return name1 + name2
fname = personal_data()
print(fname)
I've made a Python programm with a interface that receives the name of the file and a numerical data. When I create methods to manipulate filename, directory, among others, it returns an error.
I believe the error comes with object orientation. How can I solve this?
I've divided the program in two parts: one to solve my problem (no object orientation) and another to receive user data.
Error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1541, in __call__
return self.func(*args)
File "teste.py", line 60, in verificaSenha
if (Procura_nome(nome_arq) == 1):
NameError: global name 'Procura_nome' is not defined
The complete code: https://pastebin.com/Br6JAcuR
Problematic method:
def Procura_nome(nome_arq):
dir = Percorre_dir_entrada()
arquivo = dir + dir[2] + nome_arq + + ".shp"
os.path.isfile(nome_arq)
try:
with open(arquivo, 'r') as f:
return 1
except IOError:
return 0
All python method class must have self param as first argument, this argument refers to the instance of your class, also when using class methods and attributs inside your class you should refer to them with self.
You probably need to add self to all your method class in your file.
You also need to remove one '+' on the 3rd line.
def Procura_nome(self, nome_arq):
dir = self.Percorre_dir_entrada()
arquivo = dir + dir[2] + nome_arq + ".shp"
os.path.isfile(nome_arq)
try:
with open(arquivo, 'r') as f:
return 1
except IOError:
return 0
Your Percorre_dir_entrada and Percorre_dir_saida function are doing exactly the same thing on different files, you should think about doing a generic version who take the file name as param like so :
def Percorre_dir(self, file_name):
achou = 0
dirlist = os.listdir(".")
for i in dirlist:
filename = os.path.abspath(i)
if((filename.find(file_name)) != -1):
achou = 1
return filename
if(achou == 0):
return 0
then call it :
Percorre_dir("Saida")
Percorre_dir("Entrada")
When I go to run this code, I get the error above. I would understand if it was because one of my objects haven't been identified as strings but the error appears on the first file_name.write()
def save_itinerary(destination, length_of_stay, cost):
# Itinerary File Name
file_name = "itinerary.txt"
# Create a new file
itinerary_file = open('file_name', "a")
# Write trip information
file_name.write("Trip Itinerary")
file_name.write("--------------")
file_name.write("Destination: " + destination)
file_name.write("Length of stay: " + length_of_stay)
file_name.write("Cost: $" + format(cost, ",.2f"))
# Close the file
file_name.close()
You should be using itinerary_file.write and itinerary_file.close, not file_name.write and file_name.close.
Also, open(file_name, "a") and not open('file_name', "a"), unless you're trying to open a file named file_name instead of itinerary.txt.
An attribute error means that the object your trying to interact with, does not have the item inside it you're calling.
For instance
>>> a = 1
>>> a.append(2)
a is not a list, it does not have an append function, so trying to do this will cause an AttributError exception
when opening a file, best practice is usually to use the with context, which does some behind the scenes magic to make sure your file handle closes. The code is much neater, and makes things a bit easier to read.
def save_itinerary(destination, length_of_stay, cost):
# Itinerary File Name
file_name = "itinerary.txt"
# Create a new file
with open('file_name', "a") as fout:
# Write trip information
fout.write("Trip Itinerary")
fout.write("--------------")
fout.write("Destination: " + destination)
fout.write("Length of stay: " + length_of_stay)
fout.write("Cost: $" + format(cost, ",.2f"))