'Reading in a semicolon-delimited txt file in Python
I'm trying to read a .txt file on Python, line by line.
out = open('output_path\A.txt', 'w')
with open('input_path\B.txt', 'r') as foo:
for each_line in foo:
# Modify each line
One problem is that I want each line to be defined by semicolon delimiters instead of line change. How would I do that?
This is what the .txt file looks like, for instance:
%IF (&YEAR LT 2010) %THEN %DO;
PAYLC3=(1.08**(1/12)-1)*X1617;
IF (X1918>0) THEN PAYORE3=
(X1903 IN (12,14,21,22,25,40,41,42,43,44,49,50,52,999))*
X1918*(%MCONV(F=X1919))*(X1905/10000);
ELSE IF (X1923>0) THEN PAYORE3=
(X1903 IN (12,14,21,22,25,40,41,42,43,44,49,50,52,999))*
X1923*(%MCONV(F=X1924))*(X1905/10000);
ELSE PAYORE3=0;
%END;
I want to be able to set each_line as a semicolon-delimited line.
Solution 1:[1]
Did you try and use the split
function. That should give you a list with lines delimited with a ;
. split
function will be used on a string, so first read the complete data from the file.
String Split Example:
>>> a = "test;this;string;"
>>> lines = a.split(";")
>>> print lines
['test', 'this', 'string', '']
Solution 2:[2]
First replace/remove the line breaks, and then split:
a = 'this thing\n the same thing in another line\n;the other thing; and other'
print a
# this thing
# the same thing in another line
#;the other thing; and other
b = a.replace('\n','').split(';')
# b = ['this thing the same thing in another line', 'the other thing', 'and other']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Kunal Aggarwal |
Solution 2 | Peter Mortensen |