Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want read from file and store it as an array, for example :
test.txt :
1,2,7,2,3
5,8,1,6
7,4
7,4,4,4,4,4,4,4,4,0,5,4
Output:
{1,2,3,7}
{1,5,6,8}
{4,7}
{0,4,5,7}
How to fetch it as an array?
From what I understand, you want to parse your file in order to output the sets of numbers for each line, isn't it ?
If it is, a solution could be:
with open("test.txt") as f:
content = f.read()
l = [set(int(x) for x in l.split(','))
for l in content.splitlines()]
print (l)
This piece of code does not sort the set though, to do this, you will have to use frozenset as well as the sorted built-in function.
This should work.
Read from file
Split using newline character
Replace , in set
Like this
with open("test.txt",'r') as text_file: #reading in read mode
#to get the list of lines replacing new line
lines=text_file.read().split('\n')
#replace commas and make a set
set_of_lines = [ set(line.replace(",","")) for line in lines]
for line in set_of_lines:
print(line)
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
I have a large text file in Python. Firstly, I want to read the text then, delete lines which have only numbers. Then, I open a new text file and write with my changes.
If the line contains numbers and strings, I want to keep them. I tried with isdigit and regex but I couldn't...
e.g. I tried: but it deletes all lines that contain numbers.
if not all(line.isdigit() for line in text_data):
new question:
line1: 324 4234 23456
if I have a line which contains numbers and space only like line1, how I skip them to my new text file?
Strip whitespace from the line before checking if it is all numbers.
for line in text_data:
if line.strip().isdigit():
# do what is required for a line with all numbers
else:
# do what is required for an alphanumeric line
I think you just need to read the file, filter it if line is not a digit, then write it to a new file:
with open('old.txt') as old, open('new.txt', 'w') as new:
for line in filter(lambda text: not text.strip().isnumeric(), old): new.write(line)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am beginner in python and I have a file with e.g data:
123.141212412
123124.5436456
13123.123546
I am trying to convert it to inteeger.
My idea was load file to a list and format the records. But it throws an error.
I did:
file.write(str(format(list1,'.0f')))
You may perform the same in this manner :
file = open('test.txt', 'r')
# List to hold the numbers
x = []
# end = split at \n because \n is read in lines too
for line in file.read().split('\n'):
# Type casting to int
int_num = int(float(line))
# saving the int part of the data in list
x.append(int_num)
# printing the int part
print(int_num)
You cannot directly apply format on a list, you have to loop through your list to do so, like this:
for number in list1:
file.write(format(number, ".0f") + "\n")
Of course, this assumes file exists and have been correctly defined, like this:
file = open("my_filename", "w")
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have a .txt file with a variable called id=
How can I write a script that will look into that .txt file, find id= and insert a string right after the =?
I do have a separate .py file called dictionary that contains a dictionary with the purpose of finding and replacing certain words in the .txt file.
Could I also use this dictionary as a way to find and insert?
Read the file line by line, if line has 'id=' replace it with the builtin replace method of str and write the new line, else write the old line.
with open(path_to_file) as fp:
with open(path_to_new_file, 'w') as nfp:
string = "whatever"
for line in fp:
if "id=" in line:
new_line = line.replace("id=", f"id={string}")
print(f"replacing {line} with {new_line}")
nfp.write(new_line)
else:
nfp.write(line)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am trying to make a function that takes typically copy-pasted text that very often includes \n characters. An example of such is as follows:
func('''This
is
some
text
that I entered''')
The problem with this function is the text can sometimes be rather large, so taking it line by line to avoid ', " or ''' isn't plausible. A piece of text that can cause issues is as follows:
func('''This
is'''
some"
text'
that I entered''')
I wanted to know if there is any way I can take the text as seen in the second example and use it as a string regardless of what it is comprised of.
Thanks!
To my knowledge, you won't be able to paste the text directly into your file. However, you could paste it into a text file.
Use regex to find triple quotes ''' and other invalid characters.
Example python:
def read_paste(file):
import re
with open(file,'r') as f:
data = f.readlines()
for i,line in enumerate(data):
data[i] = re.sub('("|\')',r'\\\1',line)
output = str()
for line in data:
output += line
return output
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I use the following code segment to read a file in python
file = open("test.txt", "rb")
data=file.readlines()[1:]
file.close
print data
However, I need to read the entire file (apart from the first line) as a string into the variable data.
As it is, when my files contents are test test test, my variable contains the list ['testtesttest'].
How do I read the file into a string?
I am using python 2.7 on Windows 7.
The solution is pretty simple. You just need to use a with ... as construct like this, read from lines 2 onward, and then join the returned list into a string. In this particular instance, I'm using "" as a join delimiter, but you can use whatever you like.
with open("/path/to/myfile.txt", "rb") as myfile:
data_to_read = "".join(myfile.readlines()[1:])
...
The advantage of using a with ... as construct is that the file is explicitly closed, and you don't need to call myfile.close().