How to write to multiple files in Python? - python

I have two files I want to open:
file = open('textures.txt', 'w')
file = open('to_decode.txt', 'w')
Then I want to write to both of them separately:
file.write("Username: " + username + " Textures: " + textures)
file.write(textures)
The first write thing is for the first open and the second is for the second.
How would I do this?

You are overwriting the file variable with the second open, so all the writes would be directed there. Instead, you should use two variables:
textures_file = open('textures.txt', 'w')
decode_file = open('to_decode.txt', 'w')
textures_file.write("Username: " + username + " Textures: " + textures)
decode_file.write(textures)

Name your file pointers two different things, i.e. not both "file".
file1 = open...
file2 = open...
file1.write...
file2.write...
Right now, the second "file" declaration you're making is over-writing the first one, so file only points to "to_decode.txt".

You can use "with" to avoid mentioning file.close() explicitly. Then You don't have to close it - Python will do it automatically either during garbage collection or at program exit.
with open('textures.txt', 'w') as file1,open('to_decode.txt', 'w') as file2:
file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)

Just give them different names:
f1 = open('textures.txt', 'w')
f2 = open('to_decode.txt', 'w')
f1.write("Username: " + username + " Textures: " + textures)
f2.write(textures)
As others have mentioned, file is the name of a built-in function so using that name for your local variable is a bad choice.

You need to use two different variables, as #Klaus says, to create two different, distinct handles to which you can push operations. So,
file1 = open('textures.txt', 'w')
file2 = open('to_decode.txt', 'w')
then
file1.write("Username: " + username + " Textures: " + textures)
file2.write(textures)

Related

writing data in file using python

I am new in programming. Just bought a book for beginners in Python. In it I got this code:
name = input("name")
email = input("whats ure email:)
favoriteband = input("ure fav band")
outputString = name + "|" email + "|" + favoriteband
fileName = name + ".txt"
file = open(fileName, "wb")
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close ()
According to book its fine but I got this error:
TypeError: a bytes-like object is required, not 'str'
I got no clue how to fix it and book isn't explaining this as well.
Let's go through this:
name = input("Your name: ")
email = input("Your email: ")
The close quotes are needed as has been pointed out.
outputString = name + "|" + email + "|" + favoriteband
outputString was missing a + before email
Finally, we need to rewrite you file management:
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
Writing this as a with statement guarantees it will close. Using open(..., "a") opens the file in "append" mode and lets you write multiple strings to a file of the same name.
Finally, if I can editorialize, I am not a fan of this book so far.
Edit: here is the whole code with fixes, in hopes of getting you there.
name = input("name")
email = input("whats ure email:")
favoriteband = input("ure fav band")
outputString = name + "|" + email + "|" + favoriteband
fileName = name + ".txt"
with open(fileName, "a") as file:
file.write (outputString)
print (outputString , " saved in ", fileName)
You can verify it works with:
with open(fileName, "r") as file:
print(file.read())
I did some editing (closing quotes and a missing +):
name = input("name:")
email = input("whats ure email:")
favoriteband = input("ure fav band:")
outputString = name + " | " + email + " | " + favoriteband
fileName = name + ".txt"
file = open(fileName, "w") #opened in write mode but not in binary
file.write (outputString)
print (outputString , " saved in ", fileName)
file.close()
You're getting that error because you're writing in binary mode, hence the b in wb for
file = open(fileName, "wb")
Try this instead :
file = open(fileName, "w")

How do I assign values in text file to an array inside python function and use it as global?

I am using windows10 and python 2.7.14. Running the python scripts in command prompt. I want to read some lines in text file and compare with some text, if it matches it should be stored in array. And also I want the array should be global. But In my script the I am not able to store the contents in array. How do I achieve this.
#This method is to reading logfile and saving the different datas in different lists
def Readlogs(Filename):
datafile = file(Filename)
for line in datafile:
if "login = " in line:
print(line)
trial=line
s2 = "= "
ArrayLogin = trial[trial.index(s2) + len(s2):]
print(ArrayLogin)
print(ArrayLogin)
if "Overlay = " in line:
print(line)
trial2=line
s2 = "= "
arrayOverlay = trial2[trial2.index(s2) + len(s2):]
print(arrayOverlay)
Readlogs(WriteFileName)
You can declare empty arrays and append items to it.
#This method is to reading logfile and saving the different datas in different lists
def Readlogs(Filename):
#empty array
ArrayLogin, arrayOverlay = [], []
datafile = file(Filename)
for line in datafile:
if "login = " in line:
print(line)
trial=line
s2 = "= "
ArrayLogin.append(trial[trial.index(s2) + len(s2):])
print(ArrayLogin)
print(ArrayLogin)
if "Overlay = " in line:
print(line)
trial2=line
s2 = "= "
arrayOverlay.append(trial2[trial2.index(s2) + len(s2):])
print(arrayOverlay)
return ArrayLogin, arrayOverlay
arr1, arr2, = Readlogs(WriteFileName)

Python-Multiple writing the same line in txt file

I have code like this:
def export_devices():
code = input("Enter device code: ")
amount = int(input("How many devices you export: "))
with open("uredjaji.txt", "r+") as f:
current_position = 0
line = f.readline()
while line:
if line[:len(code) + 1] == code + ":":
line = line.rstrip()
amount_index = line.rfind(":") + 1
current_amount = int(line[amount_index:])
if amount > current_amount:
print("There no that many devices in stock...")
return
remaining_content = f.read()
f.seek(current_position)
f.truncate()
line = line[:amount_index] + str(current_amount - amount) + "\n"
f.write(line)
f.write(remaining_content)
return
current_position = f.tell()
line = f.readline()
with open('transakcije.txt','a') as transactions:
date = datetime.date.today().strftime('%d.%m.%Y.')
transactions.write("1" + ":" + str(amount) + ":" + "export" + ":" + str(date) + ":" + "username" + "\n")
print("Error device code: {}".format(code))
Now I would like to my "transakcije.txt" looks like this:
1:3:iznos:17.06.2017.:username
But it always append the same line for three times. With any other kind of indentation it won't append at all.
Also, my uredjaji.txt file looks like this:
tw004:Galaxy S5:Samsung:Mobilni telefon:3
tw002:Galaxy S6:Samsung:Mobilni telefon:1
tw001:Huawei P8:Huawei:Mobilni telefon:1
tw003:Huawei P9:Huawei:Mobilni telefon:100998
P.S: "username" should be variable from another function, so if someone could help me how to write that variable in this file I will be so thankfull. :)
When you open the file, you read a single line and then go into a while loop on the existence of line. If you do not get a match on the input code, you then attempt to, I suppose, reposition the file pointer with f.tell() but you do not do a seek. Thereafter, you read the file again and write transakcije.txt. Sadly, the original while loop is still in play, so you will write transakcije.txt multiple times.
It is not clear what you are attempting to achieve with this code but you need to sit down and rethink it from the ground up.
If it is some sort of stock reporting/replenishment routine, I can't help thinking that a database (sqlite3 as a simple starter) would be more appropriate that pulling ascii files apart.

How to convert from saving to a text file to saving to an excel file in python using csv

I have been programming a maths quiz and have been saving my answer to a text file however now I would like to save these to a excel file in and I have been told I would need to import cvs and use this. I have try to do this but then i have received copious amounts of error. Any answer would would much appreciated. I feel the code I have now is fairly easy to understand and is user friendly.
class_number = prompt_int_big("Before your score is saved ,are you in class 1, 2 or 3? Press the matching number")
filename = (str(class_number) + "csv")
with open(filename, 'a') as f:
f.write("\n" + str(name) + " scored " + str(score) + " on difficulty level " + str(level_of_difficulty) + "\n")
with open(filename) as f:
lines = [line for line in f if line.strip()]
lines.sort()
if prompt_bool("Do you wish to view previous results for your class"):
for line in lines:
print (line)
else:
sys.exit("Thanks for taking part in the quiz, your teacher should discuss your score with you later")

Assigning a fieldname to a variable in Python

I am new to Python and I am trying to check for nulls in the csv I am processing. I am using a DictReader object with key pair values. I am using the key pair values in the for loop to print out the information(kml in this instance).
I go to run the program and it is not liking my variable assignment. Here is the error I am receiving.
File "./csvtokml3.py", line 31
Latvariable = str(row["lat_degrees"]),Longvariable = str(row["lon_degrees"])
SyntaxError: can't assign to function call
Here is the code for the program.
#!/usr/bin/python
#
#
#
import csv
#Input the file name.
fname = raw_input("Enter file name WITHOUT extension: ")
data = csv.DictReader(open(fname + '.csv'), delimiter = ',')
#Open the file to be written.
f = open('csv2kml.kml', 'w')
#Writing the kml file.
f.write("<?xml version='1.0' encoding='UTF-8'?>\n")
f.write("<kml xmlns='http://www.opengis.net/kml/2.'>\n")
f.write("<Document>\n")
f.write(" <name>" + fname + '.kml' +"</name>\n")
for row in data:
f.write(" <Placemark>\n")
f.write(" <name>" + str(row["station"]) + "</name>\n")
### f.write(" <description>" + str(row[0]) + "</description>\n")
f.write(" <Point>\n")
#Check for nulls for lat and long
Latvariable = str(row["lat_degrees"]), Longvariable = str(row["lon_degrees"])
if Latvariable !=null and Longvariable !=null:
f.write(" <coordinates>" + str(row["lat_degrees"]) + "," + str(row["lon_degrees"]) + "</coordinates>\n")
f.write(" </Point>\n")
f.write(" </Placemark>\n")
f.write("</Document>\n")
f.write("</kml>\n")
f.close()
print "File Created. "
print "Press ENTER to exit. "
raw_input()
Your syntax is incorrect, you wanted:
Latvariable, Longvariable = str(row["lat_degrees"]), str(row["lon_degrees"])
instead to assign multiple values to multiple names. Alternatively, put the two statements on separate lines:
Latvariable = str(row["lat_degrees"])
Longvariable = str(row["lon_degrees"])
You cannot combine multiple assignment statements with commas like you tried; that works in JavaScript but not in Python.

Categories

Resources