I want to open any .txt file in the same directory.
In ruby I can do
File.open("*.txt").each do |line|
puts line
end
In python I can't do this it will give an error
file = open("*.txt","r")
print(file.read())
file.close()
It gives an error invalid argument.
So is there any way around it?
You can directly use the glob module for this
import glob
for file in glob.glob('*.txt'):
with open(file, 'r') as f:
print(f.read())
Use os.listdir to list all files in the current directory.
all_files = os.listdir()
Then, filter the ones which have the extension you are looking for and open each one of them in a loop.
for filename in all_files:
if filename.lower().endswith('.txt'):
with open(filename, 'rt') as f:
f.read()
Related
It's clear for me how to open one file and it's pretty straight forward by using open() function just like this:
with open('number.txt', 'rb') as myfile:
data=myfile.read()
But what will be my actions if I want to open 5 .txt files and also view them as a string in Python? Should I somehow use os.listdir() possibilities?
Here a flexible/reusable approach for doing exactly what you need:
def read_files(files):
for filename in files:
with open(filename, 'rb') as file:
yield file.read()
def read_files_as_string(files, separator='\n'):
files_content = list(read_files(files=files))
return separator.join(files_content)
# build your files list as you need
files = ['f1.txt', 'f2.txt', 'f3.txt']
files_content_str = read_files_as_string(files)
print(files_content_str)
Looks like you need.
import os
path = "your_path"
for filename in os.listdir(path):
if filename.endswith(".txt"):
with open(os.path.join(path, filename), 'rb') as myfile:
data=myfile.read()
I'm reading from a folder of txt files, in a loop in this way:
path = './input/*.txt'
files=glob.glob(path)
for file in files:
with open (file, 'rt') as f:
fstr= f.read()
Is there a way to know on which file the program is atm?
I want to print it.
Thanks
putonspectacles answered it: print(file) inside the loop
I want to view the first line of each file in the directory in hex
I can use a loop to do it for all of the files but i need a way to view the first few bytes of a file
any ideas ?
pushpendra chauhan's answer is correct, but why should we use a for loop when it's not necessary (we are only looping once every time!)? (I cannot comment as I don't have sufficient reputation).
The other thing is, this will raise an IOError if you have any subdirectories in your path. So I added a line using os.path to see if the current 'file' is actually a file before attempting to open it.
import os
def read_first_line(filename):
with open(filename) as f:
print f.readline()
for filename in os.listdir(os.getcwd()):
if os.path.isfile(filename): read_first_line(filename)
This will work for you : -
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir('folderPath') if isfile(join('folderPath', f))]
for file in onlyfiles:
with open(join('folderPath', file), 'r') as f:
first_line = f.readline()
print first_line
First you can read all files name in the directory
for filename in os.listdir(os.getcwd()):
and then you can read first line of each file
Here is the full code
import os
def readFile(filename):
with open(filename) as f:
for line in f:
print line
break
for filename in os.listdir(os.getcwd()):
readFile(filename)
I have files in an order something like this:
H2_000.csv,
H2_001.csv,
H2_002.csv,
H2_003.csv,
H2_004.csv,
H2_005.csv.
import glob
path = 'path/H2_*.csv'
files=glob.glob(path)
for file in files:
f=open(file, 'r')
print f
output
open file 'path/H2_003.csv', mode 'r' at 0x7f3ce9eca150,
open file 'path/H2_000.csv', mode 'r' at 0x7f3ce9eca1e0,
open file 'path/H2_004.csv', mode 'r' at 0x7f3ce9eca150,
open file 'path/H2_001.csv', mode 'r' at 0x7f3ce9eca1e0,
but this reads the file randomly,
I want the file to be open in an order.
Can any one help me. thanks!
All you need to do is sort the list of files (and also always use with)
import glob
path = 'path/H2_*.csv'
files=glob.glob(path)
for file in sorted(files):
with open(file, 'r') as f:
print f
Trying to extract all the zip files and giving the same name to the folder where all the files are gonna be.
Looping through all the files in the folder and then looping through the lines within those files to write on a different text file.
This is my code so far:
#!usr/bin/env python3
import glob
import os
import zipfile
zip_files = glob.glob('*.zip')
for zip_filename in zip_files:
dir_name = os.path.splitext(zip_filename)[0]
os.mkdir(dir_name)
zip_handler = zipfile.ZipFile(zip_filename, "r")
zip_handler.extractall(dir_name)
path = dir_name
fOut = open("Output.txt", "w")
for filename in os.listdir(path):
for line in filename.read().splitlines():
print(line)
fOut.write(line + "\n")
fOut.close()
This is the error that I encounter:
for line in filename.read().splitlines():
AttributeError: 'str' object has no attribute 'read'
You need to open the file and also join the path to the file, also using splitlines and then adding a newline to each line is a bit redundant:
path = dir_name
with open("Output.txt", "w") as fOut:
for filename in os.listdir(path):
# join filename to path to avoid file not being found
with open(os.path.join(path, filename)):
for line in filename:
fOut.write(line)
You should always use with to open your files as it will close them automatically. If the files are not large you can simply fOut.write(f.read()) and remove the loop.
You also set path = dir_name which means path will be set to whatever the last value of dir_name was in your first loop which may or may not be what you want. You can also use iglob to avoid creating a full list zip_files = glob.iglob('*.zip').