How can i append a text file to order the contents - python

I have a text file with about 2000 numbers, they are written to the file in a random order...how can i order them from within python? Any help is appreciated
file = open('file.txt', 'w', newline='')
s = (f'{item["Num"]}')
file.write(s + '\n')
file.close()
read = open('file.txt', 'a')
sorted(read)

You need to:
read the contents of the file: open('file.txt', 'r').read().
split the content using a separator: separator.split(contents)
convert each item to a number, otherwise, you won't be able to sort numerically: int(item)
sort the numbers: sorted(list_of_numbers)
Here is a code example, assuming the file is space separated and that the numbers are integers:
import re
file_contents = open("file.txt", "r").read() # read the contents
separator = re.compile(r'\s+', re.MULTILINE) # create a regex separator
numbers = []
for i in separator.split(f): # use the separator
try:
numbers.append(int(i)) # convert to integers and append
except ValueError: # if the item is not an integer, continue
pass
sorted_numbers = sorted(numbers)
You can now append the sorted content to another file:
with open("toappend.txt", "a") as appendable:
appendable.write(" ".join(sorted_numbers)

Related

Slice a given txtfile and write only part of it in a newfile in python

This is my original .txt data:
HKEY_CURRENT_USER\SOFTWARE\7-Zip
HKEY_CURRENT_USER\SOFTWARE\AppDataLow
HKEY_CURRENT_USER\SOFTWARE\Chromium
HKEY_CURRENT_USER\SOFTWARE\Clients
HKEY_CURRENT_USER\SOFTWARE\CodeBlocks
HKEY_CURRENT_USER\SOFTWARE\Discord
HKEY_CURRENT_USER\SOFTWARE\Dropbox
HKEY_CURRENT_USER\SOFTWARE\DropboxUpdate
HKEY_CURRENT_USER\SOFTWARE\ej-technologies
HKEY_CURRENT_USER\SOFTWARE\Evernote
HKEY_CURRENT_USER\SOFTWARE\GNU
And I need to have a new file where the new lines contain only part of those strings, like:
7-Zip
AppDataLow
Chromium
Clients
...
how to do it in python?
Try this:
## read file content as string
with open("file.txt", "r") as file:
string = file.read()
## convert each line to list
lines = string.split("\n")
## write only last part after "\" in each line
with open("new.txt", "w") as file:
for line in lines:
file.write(line.split("\\")[-1] + "\n")
One approach would be to read the entire text file into a Python string. Then use split on each line to find the final path component.
with open('file.txt', 'r') as file:
data = file.read()
lines = re.split(r'\r?\n', data)
output = [x.split("\\")[-1] for x in lines]
# write to file if desired
text = '\n'.join(output)
f_out = open('output.txt', 'w')
f_out.write(text)
f_out.close()

Reading from text file and storing in array [duplicate]

This question already has answers here:
Create new list from nested list and convert str into float
(4 answers)
Closed 3 years ago.
If I have a text file containing the following numbers:
5.078780 5.078993
7.633073 7.633180
2.919274 2.919369
3.410284 3.410314
How can read it and store it in an array, so that it becomes:
[[5.078780,5.078993],[7.633073,7.633180],[2.919274,2.919369],[3.410284,3.410314]]
with open('test.txt', 'r') as file:
output = [ line.strip().split(' ') for line in file.readlines()]
# Cast strings to floats
output = [[float(j) for j in i] for i in output]
print(output)
should give the desired output:
[[5.07878, 5.078993], [7.633073, 7.63318], [2.919274, 2.919369], [3.410284, 3.410314]]
Approach:
Have a result list = []
Split the text by newlines \n.
Now in a for-loop
split each line by a space char and assign to a tuple
append tuple to the result list
I'm refraining from writing code here to let you work it out.
This should do
with open ("data.txt", "r") as myfile:
data=myfile.readlines()
for i in range(len(data)):
data[i]=data[i].split()
You first want to retrieve the file content in an array of string (each string is one line of the file)
with open("myfile.txt", 'r') as f:
file_content = f.readlines()
Refer to open doc for more: https://docs.python.org/3/library/functions.html#open
Then you want to create a list
content_list = []
And then you want to fill it with each string, when each string should be split with a space(using split() function) which make a list with the two values and add it to content_list, use a for loop !
for line in file_content:
values = line.split(' ') # split the line at the space
content_list.append(values)
By the way, this can be simplified with a List Comprehension:
content_list = [s.split(' ') for s in file_content]
This should work,
with open('filepath') as f:
array = [line.split() for line in f.readlines()]
Python provides the perfect module for this, it's called csv:
import csv
def csv_to_array(file_name, **kwargs):
with open(file_name) as csvfile:
reader = csv.reader(csvfile, **kwargs)
return [list(map(float, row)) for row in reader]
print(csv_to_array('test.csv'))
If you later have a file with a different field separator, say ";", then you'll just have to change the call to:
print(csv_to_array('test.csv', delimiter=';'))
Note that if you don't care about importing numpy then this solution is even better.
To convert to this exact format :
with open('filepath', 'r') as f:
raw = f.read()
arr = [[float(j) for j in i.split(' ')] for i in raw.splitlines()]
print arr
outputs :
[[5.07878, 5.078993], [7.633073, 7.63318], [2.919274, 2.919369], [3.410284, 3.410314]]
with open('blah.txt', 'r') as file:
a=[[l.split(' ')[0], l.split(' ')[1] for l in file.readlines() ]

How to make string from a text file in Python 3?

path = "C:\\Users\\user\\Downloads\\wordlist.txt"
word_list = open(path, 'r')
list = [x for x in word_list.split(" ")]
How can I open a file, so that I can make it into a string and eventually turn that string into a list? I've tried with split(), but it seems that text files can't just be split, although they are read.
Use with open
Ex:
path = "C:\\Users\\user\\Downloads\\wordlist.txt"
l = []
with open(path, "r") as infile: #Read file
for line in infile: #Iterate over each line
l.append(line.split()) #split by space and append
word_list.readlines() will give the list itself as per row ending

Converting the file of decimal values into hex format

I am new to python and I am trying to write a simple script that will convert each row of my .txt file containing decimals into hex format and will save it into another .txt file. My input has the 16 bit values in decimal format such as
15166
46818
26814
640
44756
27831
2646
This is a snippet that I have so far:
import binascii
filename = '1.txt'
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'wb')
f.write(out)
f.close()
This is the output that I am getting 31353136360d0a34363831380d0a32363831340d0a3634300d0a34343735360d0a32373833310d0a323634360d0a393237360d0a323238390d0a333330320d0a33393137370d0a393535340d0a363239310d0a31353438310d0a33353632300d0a35373330310d0a33323933350d0a3834380d0a34313639330d0a33353538340d0a31363936390d0a31313539300d0a31343639350d0a36333931350d0a393238340d0a33323339370d0a343235330d0a33323934320d0a31303139340d0a34393238360d0a34383430370d0a31333330350d0a3336340d0a36323735340d0a32313438310d0a35323734350d0a31303931310d0a34323835380d0a373731370d0a34393530320d0a35313034380d0a36323832330d0a34343833370d0a36313934300d0a33393137310d0a33333032320d0a32333836360d0a36313335360d0a31393038380d0a35393135340d0a36353335320d0a32343233300d0a32303936310d0a34313134330d0a35343433350d0a36343038380d0a35323334340d0a33373136370d0a32363734390d0a36353439300d0a36353236360d0a36313234320d0a33343933360d0a313532360d0a35313236310d0a33353039350d0a36303931350d0a34313336350d0a32333235370d0a333133350d0a33373433380d0a34363837350d0a363831390d0a34373034320d0a31373035380d0a363734350d0a35313135340d0a333535330d0a33343134320d0a36353334360d0a34343334310d0a35333330370d0a35333232320d0a34313336300d0a33383037300d0a32363134350d0a34343532310d0a34373836360d0a34393033360d0a36323037320d0a34373630330d0a34363337300d0a34303534360d0a31393231330d0a373930340d0a393839340d0a31383337350d0a35383231360d0a33353033380d0a31333338310d0a32313637350d0a33383333370d0a35393430340d0a31333933300d0a31353830370d0a33373434370d0a31313832370d0a34383331360d0a32393433350d0a32363831360d0a36313035360d0a34303533350d0a33383335340d0a31373037370d0a34383236360d0a31363237350d0a34343331370d0a35343836320d0a34303730370d0a32363735370d0a32353438380d0a3737320d0a32363038330d0a32373339370d0a35323934380d0a34313537340d0a32363934310d0a3433353539
So I need that each entry will be separated and displayed as a list in my output file. If I do have the line
for c in out:
print(c)
I get the huge list with two decimals in each of it and seemed to be wrong. Please post any solution for this problem.
Another way to do it is using hex like so:
filename = '1.txt'
newfile = '2.txt'
with open(filename, 'r') as f:
numbers = f.read().splitlines()
with open(newfile, 'w') as n:
for num in numbers:
n.write('{}\n'.format(hex(int(num))))

Read text file to list in python

I want to create a text file which contains positive/negative numbers separated by ','.
i want to read this file and put it in data = []. i have written the code below and i think that it works well.
I want to ask if you guys know a better way to do it or if is it well written
thanks all
#!/usr/bin/python
if __name__ == "__main__":
#create new file
fo = open("foo.txt", "w")
fo.write( "111,-222,-333");
fo.close()
#read the file
fo = open("foo.txt", "r")
tmp= []
data = []
count = 0
tmp = fo.read() #read all the file
for i in range(len(tmp)): #len is 11 in this case
if (tmp[i] != ','):
count+=1
else:
data.append(tmp[i-count : i])
count = 0
data.append(tmp[i+1-count : i+1])#append the last -333
print data
fo.close()
You can use split method with a comma as a separator:
fin = open('foo.txt')
for line in fin:
data.extend(line.split(','))
fin.close()
Instead of looping through, you can just use split:
#!/usr/bin/python
if __name__ == "__main__":
#create new file
fo = open("foo.txt", "w")
fo.write( "111,-222,-333");
fo.close()
#read the file
with open('foo.txt', 'r') as file:
data = [line.split(',') for line in file.readlines()]
print(data)
Note that this gives back a list of lists, with each list being from a separate line. In your example you only have one line. If your files will always only have a single line, you can just take the first element, data[0]
To get the whole file content(numbers positive and negative) into list you can use split and splitlines
file_obj = fo.read()#read your content into string
list_numbers = file_obj.replace('\n',',').split(',')#split on ',' and newline
print list_numbers

Categories