How to read a text file into a string variable and strip newlines?
You could use:
with open('data.txt', 'r') as file:
data = file.read().replace('\n', '')
Or if the file content is guaranteed to be one-line
with open('data.txt', 'r') as file:
data = file.read().rstrip()
Python Removing [' '] from start and end of string when reading text from a file
It’s because readlines
returns a list.
If your file contained multiple lines you would have many elements in the list. But as you only have one line it is the only element in the list.
Check the IO documentation for other methods to read single lines.
How to read a text file that can be any length into separate string and integer variables in python?
Your example does not really make sense. But, if that is what you are looking for:
def conv(s):
try:
return ('int', int(s))
except ValueError:
return ('str', f"'{s}'")
cnt={}
with open('/tmp/file') as f:
for line in f:
for s in line.split():
t=conv(s)
cnt[t[0]]=cnt.get(t[0], 0)+1
print(f'{t[0]}{cnt[t[0]]} = {t[0]}({t[1]})')
Prints:
str1 = str('Start')
int1 = int(111)
int2 = int(139)
str2 = str('A')
int3 = int(122)
int4 = int(155)
str3 = str('B')
int5 = int(133)
int6 = int(217)
str4 = str('C')
int7 = int(144)
int8 = int(223)
str5 = str('Finish')
DON'T try and make variables out of these! Instead, use a dict
like so:
def conv(s):
try:
return ('int', int(s))
except ValueError:
return ('str', f"'{s}'")
cnt={}
data={}
with open('/tmp/file') as f:
for line in f:
for s in line.split():
t=conv(s)
cnt[t[0]]=cnt.get(t[0], 0)+1
data[f'{t[0]}{cnt[t[0]]}'] = t[1]
>>> data
{'str1': "'Start'", 'int1': 111, 'int2': 139, 'str2': "'A'", 'int3': 122, 'int4': 155, 'str3': "'B'", 'int5': 133, 'int6': 217, 'str4': "'C'", 'int7': 144, 'int8': 223, 'str5': "'Finish'"}
Read file into list and strip newlines
file.read()
reads entire file's contents, unless you specify max length. What you must be meaning is .readlines()
. But you can go even more idiomatic with a list comprehension:
with open('drugs') as temp_file:
drugs = [line.rstrip('\n') for line in temp_file]
The with
statement will take care of closing the file.
Removing newline at the end of a variable read from .txt file
Instead of writing it straight away to the file, how about first saving it in variables first and writing it at once.You can do it like this,
for line in search_file:
if search_registration in line:
str1 = line;
for line in search_av_speed_file:
if search_registration in line:
current_line = line.split(",")
speed_of_car = current_line[2]
print(speed_of_car)
str2 = speed_of_car
fstr=" ".join(str1,str2) #further formatting can be done here,like strip() and you can print this to see the desired result
fine_file.write(fstr)
In this way it will be much easier to format the strings as you want.
read and get specific int line of the text file into variable on python
You can simply iterate through the lines, and assign the line to a previous created string variable, if the condition is met, that the string occurs in a line of the file:
a_file = open('file.txt')
string = 'a word'
res_line = ""
for line in a_file:
if string in line:
res_line = line
print(res_line)
a_file.close()
you could also create a list which contains every line in that the string occurs:
a_file = open('file.txt')
string = 'a word'
res = [line for line in a_file if string in line]
print(res)
a_file.close()
Related Topics
Difference Between Images in 'P' and 'L' Mode in Pil
Convert a Unicode String to a String in Python (Containing Extra Symbols)
How to Select a Drop-Down Menu Value With Selenium Using Python
Pip Install' Fails For Every Package ("Could Not Find a Version That Satisfies the Requirement")
Find the Row Indexes of Several Values in a Numpy Array
How to Overcome "Datetime.Datetime Not Json Serializable"
How to Split a String into a List of Characters
Reference Template Variable Within Jinja Expression
List Comprehension Vs. Lambda + Filter
How to Get Json to Load into an Ordereddict
How to Implement an Efficient Infinite Generator of Prime Numbers in Python
How to Calculate Sum of Prime Numbers from List of Integers in Python
Convert All Strings in a List to Int