(Python) To read, extract, and store the nth letter of the desired row from a regular text file

Asked 1 years ago, Updated 1 years ago, 103 views

Hi, how are you?

I am a student studying programming.

When it comes to data processing, I want to extract n characters from a specific row of a file or m rows after a specific character, store them elsewhere, and print them out.


A=[#
asdf 2123
aser 2155
ac2r 2230
#
akmk 30rj
lmmi adl2
alkm kmsd45
#
...]

In this way, I want to extract # from the regularly written file to the previous line of # continuously and save it as a row, but I can't think of a sharp number because my knowledge is insignificant.

I'd appreciate your help.

It reveals that you are learning programming for research purposes and that you are not trying to achieve grades or financial gains.

python2.7

2022-09-22 19:02

3 Answers

I can make a code for you, but I don't have enough information for the question, so I'll just give you a hint.
Also, even if you can't think of a sharp number, it's easy to help if you implement the basic framework as much as possible and include it in your questions.

Open and read the file

FILE_PATH = "folder/data.txt"
f = open(FILE_PATH, 'r') # Print files in read mode
lines = f.readlines() # Read all the contents of the file by line and save it as an array of strings
f.close() # Close

Find the location or presence of a specific character in a string

s = "hello#world"
index = s.indexOf('#') #index is 5
index = s.indexOf('z') # is missing, so index is -1

Write File (Save)

f = open(FILE_PATH, 'w') #Putting files in write mode
f.write("hello\nworld")
f.close() # Close

FILE_PATH file contents:

hello
world

Adding a list to a list

data = []
data.append("1234")
data.append("5678")
print data # ['1234', '5678']


2022-09-22 19:02

with open('sample.txt', 'r') as rf:
    filteredStr = rf.read().split("#\n")[1:-1] # #\n, excluding first and last entries
with open('filtered_file.txt', 'w') as wf:
    wf.write(''.join(filteredStr))


2022-09-22 19:02

There are two ways to get the code split() based on # above and indexOf where # is. I think you can handle the conditions you want if you do it the way above. If you want to import data on a more complex basis, you can use the regular expression to import strings that meet your criteria.


2022-09-22 19:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.