So I already know how to open / read from a file line.. for example here’s what I wrote so far.
a=0
file_paths = sys.argv[1:]
for path in file_paths:
a=1
if(a==0):
while True:
print('\nSpecify where the path of the code is')
print('Example /home/user/desktop/code.txt \n')
path=input('Input Here: ')
if os.path.isfile(path)==True:
break
else:
print('No files found. Please try again')
with open(path,encoding="utf-8") as f:
src=f.readlines()
f.close
This opens the file given and is able to read it from the given input. However in order to actually use this for the purpose I have in mind I want to be able to add text inside of what it reads..
For example upon running the script it’ll ask you for the file
Input Here: Test
So it opens and reads the file Test
Is it possible to make it add specific text inbetween the lines that it reads?
(Sorry for this being long btw I’ll try to make a short example)
For instance: Say the contents of Test
were as follows
12345678 87654321
would it be possible to output / print after reading to
!12345678 - 234 !87654321
I’ve been searching for examples of this for around a week with no luck, not sure if I’m blind or what so I gave up and flocked over here. Any examples / thoughts would be appreciated. If not that’s okay as well.
Edit: To be more specific (as per requested) the file structure I’m trying to use will always look similar to this: inside of the Test
file it would look somewhat like this.
12345678 87654321
12312332 84173183
12378764 75446774
and aiming to output something along the lines of (it wont always be 3 or 2 numbers, just looking to add the newer parts as seen below)
!12345678 - 234 !87654321
!12312332 - 234 !84173183
!12378764 - 234 !75446774
>Solution :
There are a few ways you can do this. One simple way is to split each line by spaces and put in the surrounding text in a print statement:
for line in src:
line_parts = line.split()
print(f'!{line_parts[0]} - 234 !{line_parts[1]}')
This obviously assumes you know the structure of the file and it always has only, or at least, 2 parts separated by a space.
Another method would be to use regex but this is more complicated than is needed for such a task.
With some edits to your code to make it more pythonic, it may look something like:
path = sys.argv[1]
while not os.path.isfile(path):
print('No files found.')
print('\nSpecify where the path of the code is')
print('Example /home/user/desktop/code.txt \n')
path = input('Input Here: ')
with open(path,encoding="utf-8") as f:
src = f.readlines()
for line in src:
line_parts = line.split()
print(f'!{line_parts[0]} - 234 !{line_parts[1]}')
Assuming only the first command line argument is a path