Python: Formatting the way my program writes arrays to txt file - python

I am trying to get my program to print one item from each array to a text file and then once all the first items were written,write the second item of the array on the second line and so on.
The code I have now only prints the info on one line of text.
def write():
outFile=open("Inventory.txt","w")
for i in range(0,len(clothesItem)):
outFile.write(format(clothesItem[i],ITEM_FORMAT)+format(clothesColor[i],COLOR_FORMAT)+format(clothesAmount[i],AMOUNT_FORMAT))
outFile.close()

Change this line:
outFile.write(format(clothesItem[i],ITEM_FORMAT)+format(clothesColor[i],COLOR_FORMAT)+format(clothesAmount[i],AMOUNT_FORMAT))
To the following:
outFile.write(format(clothesItem[i], ITEM_FORMAT) + format(clothesColor[i],COLOR_FORMAT) + format(clothesAmount[i], AMOUNT_FORMAT) + "\n")
^^^^
Note the + "\n" added onto the end.

Related

Using Python rjust(8) does not seem to work on last item in list

I have text file containing comma separated values which read and output again reformatted.
102391,-55.5463,-6.50719,-163.255,2.20855,-2.63099,-7.86673
102392,11.224,-8.15971,15.5387,-11.512,-3.89007,-28.6367
102393,20.5277,-62.3261,-40.9294,-45.5899,-53.222,-1.77512
102394,188.113,19.2829,137.284,14.0548,4.47098,-50.8091
102397,-24.5383,-3.46016,1.74639,2.52063,3.31528,16.2535
102398,-107.719,-102.548,52.1627,-78.4543,-65.2494,-97.8143
I read it using this code:
with open(outfile , 'w') as fout:
with open(infile) as file:
for line in file:
linelist = line.split(",")
fout.write(" ELEM " + '{:>8}'.format(str(linelist[0]) + "\n"))
if len(linelist) == 7:
fout.write(" VALUE " + str(linelist[1][:8]).rjust(8) + str(linelist[2][:8]).rjust(8) + str(linelist[3][:8]).rjust(8) + str(linelist[4][:8]).rjust(8) + str(linelist[5][:8]).rjust(8) + str(linelist[6][:8]).rjust(8) )
fout.write("\n")
And get this output:
ELEM 102391
VALUE -55.5463-6.50719-163.255 2.20855-2.63099-7.86673
ELEM 102392
VALUE 11.224-8.15971 15.5387 -11.512-3.89007-28.6367
ELEM 102393
VALUE 20.5277-62.3261-40.9294-45.5899 -53.222-1.77512
ELEM 102394
VALUE 188.113 19.2829 137.284 14.0548 4.47098-50.8091
ELEM 102397
VALUE -24.5383-3.46016 1.74639 2.52063 3.3152816.2535
ELEM 102398
VALUE -107.719-102.548 52.1627-78.4543-65.2494-97.8143
Everything is fine except: Why do I get a extra blank line sometimes, and why is the last number before the blank line (16.2535) not rightadjusted? These two issues certainly belong to each other but i can not figure out what is going on.
It behaves like the last element of the fifth line of your input contins a 'newline' character at its end.
Can you check the content of linelist[6] for the fifth line of your input? I guess you would find something like: '16.2535\n'.
Hence,to make sure that your content does not include trailing newlines at the end of the string, you can use the String function .strip()

Reformatting a txt file with characters at index positions using python

Very newbie programmer asking a question here. I have searched all over the forums but can't find something to solve this issue I thought there would be a simple function for. Is there a way to do this?
I am trying to reformat a text file so I can use it with the pandas function but this requires my data to be in a specific format.
Currently my data is in the following format of a txt file with over 1000 lines of data:
["01/09/21","00:28",7.1,75,3.0,3.7,3.7,292,0.0,0.0,1025.8,81.9,17.1,44,3.7,4.6,7.1,0,0,0.00,0.00,3.0,0,0.0,292,0.0,0.0]
["01/09/21","00:58",7.0,75,2.9,5.1,5.1,248,0.0,0.0,1025.9,81.9,17.0,44,5.1,3.8,7.0,0,0,0.00,0.00,1.9,0,0.0,248,0.0,0.0
]["01/09/21","01:28",6.9,74,2.6,4.1,4.1,248,0.0,0.0,1025.8,81.9,17.0,44,4.1,4.1,6.9,0,0,0.00,0.00,2.5,0,0.0,248,0.0,0.0
I need it as
["01/09/21","00:28",7.1,75,3.0,3.7,3.7,292,0.0,0.0,1025.8,81.9,17.1,44,3.7,4.6,7.1,0,0,0.00,0.00,3.0,0,0.0,292,0.0,0.0]
["01/09/21","00:58",7.0,75,2.9,5.1,5.1,248,0.0,0.0,1025.9,81.9,17.0,44,5.1,3.8,7.0,0,0,0.00,0.00,1.9,0,0.0,248,0.0,0.0]
This requires adding a [" at the start and adding a " at the end of the date before the comma, then adding another " after the comma and another " at the end of the time section. At the end of the line, I also need to add a ], at the end.
I thought something like this would work but the second bracket appears after the line break (\n) is there any way to avoid this?
infile=open(infile)
outfile=open(outfile, 'w')
def format_line(line):
elements = line.split(',') # break the comma-separated data up
for k in range(2):
elements[k] = '"' + elements[k] + '"' # put quotes around the first two elements
print(elements[k])
new_line = ','.join(elements) # put them back together
return '[' + new_line + ']' # add the brackets
for line in infile:
outfile.write(format_line(line))
outfile.close()
You are referring to a function before it is defined.
Move the definition of format_line before it is called in the for loop.
When I rearranged your code it seems to work.
New code:
outfile=open("outputfile","w")
def format_line(line):
elements = line.split(',') # break the comma-separated data up
for k in range(2):
elements[k] = '"' + elements[k] + '"' # put quotes around the first two elements
new_line = ','.join(elements) # put them back together
return '[' + new_line + ']' # add the brackets
for line in infile:
format_line(line)

Remove lines from file what called from list

I want to remove lines from a .txt file.
i wanna make a list for string what i want to remove but the code will paste the lines as many times
as many string in list. How to avoid that?
file1 = open("base.txt", encoding="utf-8", errors="ignore")
Lines = file1.readlines()
file1.close()
not_needed = ['asd', '123', 'xyz']
row = 0
result = open("result.txt", "w", encoding="utf-8")
for line in Lines:
for item in not_needed:
if item not in line:
row += 1
result.write(str(row) + ": " + line)
so if the line contains the string from list, then delete it.
After every string print the file without the lines.
How to do it?
Look at the logic in your for loop... What it's doing is: take each line in lines, then for all the items in not_needed go through the line and write if condition is verified. But condition verifies each time the item is not found.
Try thinking about doing the inverse:
check if a line is in non needed.
if it is do nothing
otherwise write it
Expanded answer:
Here's what I think you are looking for:
for line in Lines:
if item not in not_needed:
row += 1
result.write(str(row) + ": " + line)

Python two nested loops: why the second loop runs only once? [duplicate]

This script is meant to read through a file and take in the number (numA) and the text next to it (sourceA). It then uses this and compares it to every other line in the file. If a match in "nums" is found but not in sources, it writes the num to a file along with the sources it appears in.
with open(sortedNums, "r")as sor:
for line in sor:
NumsA, sourceA = line.split('####')
for line in sor:
if '####' in line:
NumsB, sourceB = line.split('####')
if (NumsA == NumsB) & (sourceA != sourceB):
print("Found reused Nums")
with open(reusedNums, 'a')as reused:
reused.write(NumsA + ' ' + sourceA + ' ' + sourceB)
print ("setA: " + NumsA + ' ' + sourceA)
print ("setB: " + NumsB + ' ' + sourceB)
Most of this is working except that it does the full inner loop but only the first iteration of the outer loop
You are trying to read twice from the same file. Files use a current position to determine what to read next, and iterating over the remaining lines in the inner loop, you moved that position all the way to the end.
You could 'fix' that by seeking back to the start of the file with:
sor.seek(0)
However, looping over the whole file for every line in that file is really inefficient. Use a dictionary to track if you have seen the same information on a previous line:
with open(sortedNums, "r")as sor, \
open(reusedNums, 'a') as reused:
seen = {}
for line in sor:
if not '####' in line:
continue
nums, source = line.rstrip().split('####')
if nums in seen and seen[nums] != source:
print("Found reused Nums")
reused.write('{} {} {}\n'.format(nums, source, seen[nums]))
seen[nums] = source
By storing data in a dictionary, you only have to loop over the file once.

Calculating size of content

Below is the code snippet. I have a file.
f = open(self.reportSavePath,'w')
self.test = '';
for file in file_sorted:
f.write(str(os.path.getmtime(file)) + "|" + file + "\r\n")
self.test = self.test + str(os.path.getmtime(file)) + "|" + file + "\r\n"
f.close()
print("Size:",os.path.getsize(self.reportSavePath)) #Without opening file
print("Calculated size:",len(self.test.encode())) #After reading the contents
My question is, why are the last two lines giving different output? Should they not be same?
If there is a reason, how can I edit line with comment #Without opening file to match the output with line commented #After reading the contents?
You're comparing apples and oranges.
os.path.getsizeof returns the file size. len(some_string) returns the length of the string in characters regardless of encoding, which can affect the naive byte count.

Categories