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
Related
I have a file (list.txt) with huge array like this:
['1458575', '1458576', '1458577', '1458578'...]
I want to read it in my script but the output is white. The goal is print the number of line (list.txt) of the file.txt
numbers_line = open("list.txt", "r")
lines = numbers_line.readlines().split(',')
i=0
f=open('file.txt')
for line in f:
if i in lines:
print (line)
i+=1
However, if I put the array direct it's read, but considering that is a huge array this is not could be helpful.
lines=['1458575', '1458576', '1458577', '1458578', '1458579', '1458580', '1458581', '1458582', '1458583', '1458584']
i=0
f=open('file.txt')
for line in f:
if i in lines:
print (line)
i+=1
Thanks for your support
readlines returns list of lines, not string
readline will return a string, but split(',') would give a list of string not int
try this
import ast
text_file = open("list.txt", "r")
lines = list(map(int, ast.literal_eval(text_file.read().strip())))
i=0
f=open('file.txt')
for line in f:
if i in lines:
print (line)
i+=1
This can work
with open('file.txt') as file:
content = file.read()
a = []
exec('a = ' + content) # executes - a = ['1458575', ...]
Alternate method - copy file.txt to new file my_lists.py.
Add 'a = ' at the start of my_lists.py file and execute
from my_lists import a
Use with open() as : instead of open() and close(), because it closes the connection to file automatically when errors occurs while the traditional manual open() and close() don't do.
lines=['1458575', '1458576', '1458577', '1458578', '1458579', '1458580', '1458581', '1458582', '1458583', '1458584']
lines = [int(x) for x in lines] # convert to integers
fpath = "list.txt"
with open(fpath, "r") as f:
for x in f:
x = x.trim() # remove end of line character
if int(x) in lines:
print(x)
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() ]
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)
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
Question:
How can I open a file in python that contains one integer value per line. Make python read the file, store data in a list and then print the list?
I have to ask the user for a file name and then do everything above. The file entered by the user will be used as 'alist' in the function below.
Thanks
def selectionSort(alist):
for index in range(0, len(alist)):
ismall = index
for i in range(index,len(alist)):
if alist[ismall] > alist[i]:
ismall = i
alist[index], alist[ismall] = alist[ismall], alist[index]
return alist
I think this is exactly what you need:
file = open('filename.txt', 'r')
lines = [int(line.strip()) for line in file.readlines()]
print(lines)
I didn't use a with statement here, as I was not sure whether or not you intended to use the file further in your code.
EDIT: You can just assign an input to a variable...
filename = input('Enter file path: ')
And then the above stuff, except open the file using that variable as a parameter...
file = open(filename, 'r')
Finally, submit the list lines to your function, selectionSort.
selectionSort(lines)
Note: This will only work if the file already exists, but I am sure that is what you meant as there would be no point in creating a new one as it would be empty. Also, if the file specified is not in the current working directory you would need to specify the full path- not just the filename.
Easiest way to open a file in Python and store its contents in a string:
with open('file.txt') as f:
contents = f.read()
for your problem:
with open('file.txt') as f:
values = [int(line) for line in f.readlines()]
print values
Edit: As noted in one of the other answers, the variable f only exists within the indented with-block. This construction automatically handles file closing in some error cases, which you would have to do with a finally-construct otherwise.
You can assign the list of integers to a string or a list
file = open('file.txt', mode = 'r')
values = file.read()
values will have a string which can be printed directly
file = open('file.txt', mode = 'r')
values = file.readlines()
values will have a list for each integer but can't be printed directly
f.readlines() read all the lines in your file, but what if your file contains a lot of lines?
You can try this instead:
new_list = [] ## start a list variable
with open('filename.txt', 'r') as f:
for line in f:
## remove '\n' from the end of the line
line = line.strip()
## store each line as an integer in the list variable
new_list.append(int(line))
print new_list