How to use 'python read space delimited file' in Python

Every line of 'python read space delimited file' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
147def readFile(some_file):
148 """
149 Reads an ascii file if it exists, removes blank lines, whitespace, and
150 comments (denoted by #). It then splits values by whitespace, giving a list
151 of all values in the file.
152
153 Example:
154 The file:
155 1 2 3
156 4
157 5
158 6 7
159 Gives:
160 ['1','2','3','4','5','6','7']
161
162 """
163
164 # Make sure the file is truly a file
165 if os.path.isfile(some_file):
166
167 # Read in the file
168 f = open(some_file)
169 lines = f.readlines()
170 f.close()
171
172 # Strip out comments, extra whitespace, and blank lines
173 lines = [l for l in lines if l[0] != "#"]
174 lines = [l.strip() for l in lines if len(l.strip()) != 0]
175
176 values = "".join(lines)
177 values = values.split()
178
179 return values
180
181 else:
182 raise IOError("%s does not exist" % some_file)
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

111def read_file(file_to_read, delimiter=';', encoding='utf-8-sig', skip=0):
112 def get_real_header(header):
113 """ Get real header cut at the first empty column """
114 new_header = []
115 for head in header:
116 if head:
117 new_header.append(head)
118 else:
119 break
120 return new_header
121
122 def check_id_column(header):
123 try:
124 header.index('id')
125 except ValueError as ve:
126 log_error("No External Id (id) column defined, please add one")
127 raise ve
128
129 def skip_line(reader):
130 log_info("Skipping until line %s excluded" % skip)
131 for _ in xrange(1, skip):
132 reader.next()
133
134 log('open %s' % file_csv)
135 file_ref = open(file_csv, 'r')
136 reader = UnicodeReader(file_ref, delimiter=separator, encoding='utf-8-sig')
137 header = reader.next()
138 header = get_real_header(header)
139 check_id_column(header)
140 skip_line(reader)
141 data = [l for l in reader]
142 return header, data

Related snippets