I think you have some slicing issues for example lets say your input is 12 0.1 0.1 0.25 line[1:] is going to be 2 0.1 0.1 0.25 because your input is a string. You can use something like:
line = '12 0.1 0.1 0.25'.split(' ') #convert your string to a list
temp = int(line[0]) #get first element and convert to integer to make comparisons easier
if temp < 3:
print(' '.join(line))
elif temp == 5:
line[0] = '4'
print(' '.join(line))
elif temp == 7:
line[0] = '5'
print(' '.join(line))
elif temp > 8:
line[0] =str(temp - 3)
print(' '.join(line))
#Output:
9 0.1 0.1 0.25
Note: It's better to use elif instead of if in your case because if one of your conditions are true it is not going to check rest of the conditions. More info here
This is one approach.
Ex:
for file_name in list_of_files:
data = []
with open(file_name) as infile:
for line in infile:
if line.startswith("2 "): #Check line
line = " ".join(['7'] + line.split()[1:]) #Update line
data.append(line)
with open(file_name, "w") as outfile: #Write back to file
for line in data:
outfile.write(line+"\n")
The proper solution is (pseudo code):
open sourcefile for reading as input
open temporaryfile for writing as output
for each line in input:
fix the line
write it to output
close input
close output
replace sourcefile with temporaryfile
We use a temporary file and write along to avoid potential memory errors.
I leave it up to you to translate this to Python (hint: that's quite straightforward).
You can only read the whole file, call .replace() for the first line and write it to the new file.
with open('in.txt') as fin:
lines = fin.readlines()
lines[0] = lines[0].replace('old_value', 'new_value')
with open('out.txt', 'w') as fout:
for line in lines:
fout.write(line)
If your file isn't really big, you can use just .join():
with open('out.txt', 'w') as fout:
fout.write(''.join(lines))
And if it is really big, you would probably better read and write lines simultaneously.
You can hack this provided you accept a few constraints. The replacement string needs to be of equal length to the original string. If the replacement string is shorter than the original, pad the shorter string with spaces to make it of equal length (this only works if extra spaces in your data is acceptable). If the replacement string is longer than the original you can not do the replacement in place and need to follow Harold's answer.
with open('your_file.txt', 'r+') as f:
line = next(f) # grab first line
old = 'NaN'
new = '0 ' # padded with spaces to make same length as old
f.seek(0) # move file pointer to beginning of file
f.write(line.replace(old, new))
This will be fast on any length file.
You can use the readlines and writelines to do this. For example, I created a file called "test.txt" that contains two lines (in Out[3]). After opening the file, I can use f.readlines() to get all lines in a list of string format. Then, the only thing I need to do is to replace the first element of the string to whatever I want, and then write back.
with open("test.txt") as f:
lines = f.readlines()
lines # ['This is the first line.\n', 'This is the second line.\n']
lines[0] = "This is the line that's replaced.\n"
lines # ["This is the line that's replaced.\n", 'This is the second line.\n']
with open("test.txt", "w") as f:
f.writelines(lines)
Reading and writing content to the file is already answered by @Zhang.
I am just giving the answer for efficiency instead of reading all the lines.
Use: shutil.copyfileobj
from_file.readline() # and discard
to_file.write(replacement_line)
shutil.copyfileobj(from_file, to_file)
Reference
When you are calling replace() it replaces every instance of that character in the string. Instead, just isolate the first character using [0] so that it will only replace there. e.g:
this_file.write(line[0].replace(s,'2'))
EDIT: I see that someone commented the same thing as i was typing mine
try this
import os
os.chdir(r" **write Folder Path here** ")
for paths,folders,files in os.walk(os.getcwd()):
for file in files:
if file.endswith("txt"):
reading_file = open(file,"r")
new_str = ""
for line in reading_file:
new_line=(line[0].replace(line[0],'0')+line[1:])
new_str += new_line
writing_file = open(file,"w")
writing_file.write(new_str)
writing_file.close()
you are not using method calls properly. ie, you are defining stringMix as a function, but using variables that are out of the scope of the function. I think what you are trying to do is:
def stringMix(a,b):
print (a.replace([0:2]b[0:2]))
print (b.replace([0:2],a[0:2]))
userStringA = input("Please enter a string consisting of over two characters ")
userStringB = input("Please enter a second string consisting of over two characters ")
print (userStringA)
print (userStringB)
stringMix(userStringA,userStringB)
However, as previous answers and comments suggest, str.replace is not really the way to do this. you should instead do:
def stringMix(a,b):
print (a[0:2]+b[2:])
print (b[0:2]+a[2:])
to take advantage of string slicing and concatenating
Simply do:
print userStringB[:2] + userStringA[2:]
and
print userStringA[:2] + userStringB[2:]